I have a list of 45 ggplot objects that I'm arranging across multiple pages thanks to the marrangeGrob() function from gridExtra. I would like to show a same and unique legend on each pages.
I know how to extract the legend (g_legend), how to plot my ggplot without the legend. But I do not find a way to have a multipages thanks to marrangeGrob and a unique legend.
I used g_legend() to extract my legend
g_legend<-function(a.gplot){
g <- ggplotGrob(a.gplot + theme(legend.position = "right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
return(legend)}
In order to simplify, the reproductible data set is from diamonds, and let say I want to produce on one page p1 and p2 and on an other page p2 and p1.
df <- count(diamonds, cut)
p1 = ggplot(df, aes(x=cut, y=n, label=format(n, big.mark=","), fill=cut)) +
geom_bar(stat="identity") +
geom_text(aes(y=0.5*n), colour="white") +
coord_flip() +
theme(legend.position="bottom")
p2 = ggplot(diamonds %>% sample_n(1000), aes(x=carat, y=price, colour=cut)) +
geom_point()
leg = g_legend(p1)
I first try to plot the 4 graphs in one page
combined<-arrangeGrob(do.call("arrangeGrob",c(
lapply(list(p1,p2,p2,p1), function(x){ x + theme(legend.position="none")}),ncol=2)),
leg,
ncol = 2)
grid.newpage()
grid.draw(combined)
which works perfectly but when I try to do it with multipages
marrangeGrob(do.call("marrangeGrob",c(lapply(list(p1,p2,p2,p1), function(x){ x + theme(legend.position="none")}),
ncol=2,nrow=2)),
leg,
ncol = 2,nrow=1)
I obtained :
Error in $<-.data.frame
(*tmp*
, "wrapvp", value = list(x = 0.5, y = 0.5, : replacement has 17 rows, data has 5
Does anyone know a way to use marrangeGrob and obtain a unique legend on each multipages?