I want to align the legend in a plot with the plotting area. I've tried many alterations of this MWE
library(ggplot2) g <- ggplot(mtcars) + geom_col(aes(x = cyl, y = mpg, fill = as.factor(am))) + theme( 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)) g
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