Placing ggplot2 legend elements in a grid

I have a legend with 4 different entries that I would like to arrange in a 2x2 grid instead of horizontal or vertical. I retrieve the legend for separate use, so I need this somewhat unusual location. Any ideas?

The code below generates a legend with all vertical positions in one column:

require(ggplot2) library(grid) library(gridExtra) dat <- data.frame(x=c(1,2,1,2,1,2,1,2),y=c(1,2,3,4,2,3,4,5),color=factor(c("a","a","b","b","c","c","d","d"))) p = ggplot(dat) p = p + geom_line(aes(dat$x,dat$y,color=dat$color)) p = p + scale_colour_manual (values=dat$color,name="") #print(p) 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]] return(legend)} legend <- g_legend(p) grid.arrange(legend) 
+4
source share
1 answer

Try adding guides(colour = guide_legend(nrow = 2)) to your plot.

+6
source

Source: https://habr.com/ru/post/1433022/


All Articles