ggplot separate legend and plot

You can get the legend from the grob object of the ggplot. Then you could use the grid.arrange function to position everything.

library(gridExtra)
g_legend<-function(a.gplot){
    tmp <- ggplot_gtable(ggplot_build(a.gplot))
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
    legend <- tmp$grobs[[leg]]
    legend
}

legend <- g_legend(plot1)

grid.arrange(legend, plot1+ theme(legend.position = 'none'), 
    ncol=2, nrow=1, widths=c(1/6,5/6))

There are lots of examples on the web using the g_legend function.

HTH

Leave a Comment