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)
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.
Changing the order of legend labels can be achieved by reordering the factor levels of the Species variable mapped to the color aesthetic.
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.
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.
Try adding guides(colour = guide_legend(nrow = 2))
to your plot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With