2
votes

I have a panel with 5 plots and one shared legend, which i would like to arrange in a (2 rows, 3 columns)-grid. The bottom right panel should be used for the legend.

library(ggplot2)
library(cowplot)
df <-data.frame(a=seq(1,20),b=seq(1,20), c=as.factor(c(rep("A", 10),rep("B",10))))
O <- ggplot(df, aes(x = a, y = b)) + geom_point(aes(col=c))
legend <- get_legend(O)

A <- ggplot(df, aes(x = a, y = b)) + geom_point(aes(col=c), show.legend = F)
B <- ggplot(df, aes(x = c, y = b)) + geom_boxplot(aes(col=c), show.legend = F)
C <- ggplot(df, aes(x = a, y = b)) + geom_line(aes(group=c, col=c), show.legend=F)
D <- ggplot(df, aes(a)) + geom_histogram()



lol <- plot_grid(A, B, C,
                 D, A, NULL, ncol=3, nrow=2, 
                 align="hv", rel_widths = c(1, 1, 1, 1, 1, 1),
                 labels = c('A', 'B', 'C', 'D', 'E', ''))

This follows the tutorial given here: https://cran.r-project.org/web/packages/cowplot/vignettes/shared_legends.html

Now the question, i tinkered with with last plot command in the vignette:

lol + draw_grob(legend, 2/3.3, 0, .3/3.3, 1)

but i cannot grasp the logic of the (apparent?) coordinate system given in the draw_grob arguments. Can someone clarify how to navigate the legend to the empty spot?

Note, that i cannot use the object 'legend' in 'plot_grid', because it prevents the alignment from working.

1

1 Answers

1
votes

You need to see it as a rectangle with the point (x, y) as the lower left corner, and the upper right corner at (x + width,y+height`).

So, in this case:

lol + draw_grob(legend, 2/3, 0, 1/3, 0.5)

enter image description here

Note that you might want increase y a bit to put it level with the actual plotting area of the other plots, instead of the whole canvas.