2

I'm using the commonly referenced g_legend function to pull a legend out of a graph made with ggplot2 such that I can organize it with multiple plots using grid.arrange. I want the legend to be a single row of elements such that I can easily put it at the bottom of my grid. However, regardless of format on the original plot, g_legend always returns a legend with a single column. Does anyone know of a way to force the legend to only have a single row?

#extract legend
#https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
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)}
dtjaeger
  • 21
  • 2
  • Have you tried `nrow` parameter in `guide_legend`? See http://docs.ggplot2.org/0.9.2.1/guide_legend.html – sckott Nov 05 '13 at 22:10
  • Yeah, I tried setting nrow = 1 and still ended up with a legend of a single column with 3 rows. – dtjaeger Nov 05 '13 at 22:23
  • I am able to change the legend format on the original ggplot figure, but when I pull it out using the g_legend function, it always reverts back to the default configuration. – dtjaeger Nov 05 '13 at 22:29
  • no experience using this approach, sorry :( – sckott Nov 05 '13 at 23:00
  • do you have a reproducible example? – baptiste Nov 06 '13 at 00:16
  • Thanks for the help, but I found an error in my code that fixed the problem. Using the nrow parameter in guide_legend does give a single row legend. I just wasn't pulling the legend from the right plot. Sorry, and thanks again. – dtjaeger Nov 06 '13 at 00:24

1 Answers1

3

I had the same problem, and I've just solved it. You have to add legend options to your "p1.leg":

p1.leg <- ggplot(data,aes(v1, v2,colour=v3))+geom_area() + theme(legend.direction = "horizontal", legend.position = "bottom")
p1 <- ggplot(data, aes( v1, v2),

Then it works.

ashatte
  • 5,442
  • 8
  • 39
  • 50
flowflow
  • 121
  • 1
  • 3