nouse
nouse

Reputation: 3471

Align shared legends to the center of the plot grid (with cowplot)

The reproducible example can be found in this tutorial for the package cowplot.

https://cran.r-project.org/web/packages/cowplot/vignettes/shared_legends.html

Copying example code:

library(ggplot2)
library(cowplot)
#down-sampled diamonds data set
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]

# Make three plots.
# We set left and right margins to 0 to remove unnecessary spacing in the
# final plot arrangement.
p1 <- qplot(carat, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt"))
p2 <- qplot(depth, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt")) + ylab("")
p3 <- qplot(color, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt")) + ylab("")

# arrange the three plots in a single row
prow <- plot_grid( p1 + theme(legend.position="none"),
           p2 + theme(legend.position="none"),
           p3 + theme(legend.position="none"),
           align = 'vh',
           labels = c("A", "B", "C"),
           hjust = -1,
           nrow = 1
           )
legend_b <- get_legend(p1 + theme(legend.position="bottom"))

# add the legend underneath the row we made earlier. Give it 10% of the height
# of one plot (via rel_heights).
p <- plot_grid( prow, legend_b, ncol = 1, rel_heights = c(1, .2))
p

This example shows a plot in which the legend is drawn aligned to the bottom left of the grid. However, it used to be differently, as the legend was then drawn aligned to the bottom center of the plot. Here is an example generated by my personal code some months ago. https://s1.postimg.org/8pf2en1zen/Untitled.png (Upload tool currently not working for me)

Rerunning my old code after an unknown amount of changes in either packages delivers a legend aligned to the bottom left (as also shown in the tutorial, third plot from above): https://s1.postimg.org/3agjw7n9gf/Untitled2.png

The question is how to adjust the code to draw the legend aligned to bottom center.

Upvotes: 5

Views: 5644

Answers (1)

Zeinab Ghaffarnasab
Zeinab Ghaffarnasab

Reputation: 818

you can set legend_b this way:

legend_b <- get_legend(p1 + theme(legend.position=c(0.3,0.8),legend.direction = "horizontal"))

a better way:

legend_b <- get_legend(p1 + theme(legend.direction = "horizontal",legend.justification="center" ,legend.box.just = "bottom"))

Upvotes: 17

Related Questions