How to position the legend at the bottom after adjusting plot.margin in ggplot2?

Advertisements

In ggplot2, I would like to increase the bottom plot margin (using the plot.margin argument of theme()) and position the legend at the bottom of the plot window.

Consider the following example code:

library("ggplot2")

d <- data.frame(x = c(8,6,5,1,8,9,6,4),
                y = c(6,5,4,3,7,1,6,4),
                v = rep(c("a","b"), each = 4))
p <- ggplot(d, aes(x, y, colour = v)) + geom_point()
p + 
  theme(plot.margin = unit(c(1,1,4,1), "cm"),
        legend.position = "bottom")

which produces the following output:

As you can see, the above plot has a large bottom margin (as specified by the plot.margin argument in the original code). But the legend is not at the bottom of the plot window, despite the legend.position argument being set to "bottom". It looks like the additional bottom margin space has been added to the plot after the legend was put at the bottom… I want to do it the other way around (i.e. increase the bottom margin and then put the legend at the bottom of the plot window).

In ggplot2, how do we position the legend at the bottom of a plot window that has an increased bottom margin?

Many thanks for any help!

>Solution :

Setting legend.position = "bottom" adds the legend at the bottom of the plotting panel, not at the bottom of the entire plot image. It sounds like you want to increase the space between the x-axis and the legend instead. One option is to add a margin to the x-axis title text:

p + 
  theme(plot.margin = margin(1, 1, 1, 1, unit = "cm"),
        axis.title.x = element_text(margin = margin(b = 3, unit = "cm")),
        legend.position = "bottom")

  • updated to use newer margin syntax instead of unit

Leave a ReplyCancel reply