Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arranging ggplot2 legend items in a grid

Tags:

r

ggplot2

I have a legend with 4 different entries that I would like to arrange in a 2x2 grid instead of horizontally or vertically. I'm extracting the legend for separate use, which is why I need this somewhat unusual arrangement. Any ideas?

The code below generates the legend with all entries vertically in a single 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)
like image 603
mlubin Avatar asked Sep 07 '12 18:09

mlubin


People also ask

How do you reorder items in legend?

You can change the order of the items in the legend in two principle ways: Refactor the column in your dataset and specify the levels. This should be the way you specified in the question, so long as you place it in the code correctly. Specify ordering via scale_fill_* functions, using the breaks= argument.

How do I change the order of labels in Ggplot legend?

Changing the order of legend labels can be achieved by reordering the factor levels of the Species variable mapped to the color aesthetic.

How do you set the position of a legend in R?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do I arrange multiple Ggplots?

To arrange multiple ggplots on one single page, we'll use the function ggarrange()[in ggpubr], which is a wrapper around the function plot_grid() [in cowplot package]. Compared to the standard function plot_grid(), ggarange() can arrange multiple ggplots over multiple pages.


1 Answers

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

like image 150
Matthew Plourde Avatar answered Sep 22 '22 13:09

Matthew Plourde