Align legend with plot axis

I want to align the legend in a plot with the plotting area. I've tried many alterations of this MWE


g <- ggplot(mtcars) +
  geom_col(aes(x = cyl, y = mpg, fill = as.factor(am))) +
    legend.position = "top",
    legend.justification = "center",
    legend.background = element_rect(fill = c("#f2f0f2"), colour = NA),
    legend.margin = margin(t = 0, r = 1, b = 0, l = 0, unit = "npc"),
    complete = T
  ) +
  theme(plot.background = element_rect(fill = "white", colour = NA))


However, it doesn't align as I need, and I obtain this result:

How can I do that? This looks so complicated, and I tried all of the StackOverflow-related posts with no success.

The final idea should be this

@Yarnabrina Hi. I updated the post to reflect the final result

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.