Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot separate legend and plot

Tags:

r

legend

ggplot2

I am using the grid lpackage to place my graphs that I made with ggplot2:

library(ggplot2)
library(grid)

Layout <- grid.layout(nrow = 4, ncol = 4,
          widths = unit(1, "null"), 
          heights = unit(c(0.4, 0.8, 1.2, 1.2), c("null", "null", "null")))
grid.show.layout(Layout)

plot1 = ggplot(diamonds, aes(clarity, fill = color)) + 
            geom_bar() + 
            facet_wrap(~cut, nrow = 1)
print(plot1 + theme(legend.position = "none"), 
vp = viewport(layout.pos.row = 3, layout.pos.col = 1:4))

The problem is that I want to put the plot on the third row (3,1) - (3,4) and put the legend at the (4,4) position. Unfortunately, I can't really find a way to create just a legend variable. I searched online and the closest that I got was using the older + opts(keep = "legend_box") but that has been deprecated.

older solution.

like image 721
user1690049 Avatar asked Sep 21 '12 23:09

user1690049


People also ask

How do I get rid of the legend in ggplot2?

Example 1: Remove All Legends in ggplot2 We simply had to specify legend. position = “none” within the theme options to get rid of both legends.

How do I add a legend in ggplot2?

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.


1 Answers

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

like image 50
Jase_ Avatar answered Oct 19 '22 17:10

Jase_