Presentation of the plot, extracted from grob separately

I have a ggplot object:

ggplot(plot1,aes(x = c, y = value, colour = variable, linetype = variable,size = variable)) + 
    geom_line() + 
    scale_x_continuous(breaks=seq(1,10,1)) +
    #scale_y_continuous(breaks=seq(0,1, 0.1))+
    scale_colour_manual(values=c("blue3","red3")) + 
    scale_linetype_manual(values = c(3,1)) + 
    scale_size_manual(values = c(0.6,0.3)) + 
    xlab("b") + 
    ylab("a") +
    theme_bw() +
    theme(axis.text=element_text(size=5),
          axis.title=element_text(size=5),
          axis.line = element_line(size=0.25),
          axis.ticks=element_line(size=0.25),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.border = element_blank(),
          panel.background = element_blank(),
          legend.position="right" ,
          legend.direction="vertical", 
          legend.title=element_blank(),
          legend.text=element_text(size=8), 
          legend.background=element_blank(), 
          legend.key=element_blank())

I would like to build the corresponding legend separately.

Is there any way to extract it?

I tried to use this function to save the legend as grob, but it only returns an empty quartz window, but without a legend.

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)}

source: https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

+3
source share
1 answer

Using a simple version of your code:

# base plot
p1 <- ggplot(plot1,aes(x=c, y=value, colour=variable, linetype=variable, size=variable)) + 
    geom_line()

# extract the different legends
leg1 <- p1 + guides(linetype=FALSE, size=FALSE)
leg2 <- p1 + guides(colour=FALSE, size=FALSE)
leg3 <- p1 + guides(colour=FALSE, linetype=FALSE)
legend.colour <- gtable_filter(ggplot_gtable(ggplot_build(leg1)), "guide-box") 
legend.linetype <- gtable_filter(ggplot_gtable(ggplot_build(leg2)), "guide-box") 
legend.size <- gtable_filter(ggplot_gtable(ggplot_build(leg3)), "guide-box") 

leg1Grob <- grobTree(legend.colour)
leg2Grob <- grobTree(legend.linetype)
leg3Grob <- grobTree(legend.size)

p2 <- p1 + guides(colour=FALSE, linetype=FALSE, size=FALSE)

# final plot were you can place the legends were you want them
finplot <- p2 +
  annotation_custom(grob = leg1Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??) +
  annotation_custom(grob = leg2Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??) +
  annotation_custom(grob = leg3Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??)

Replace ??with the coordinates of your plot if you want to place your legends.

If you want to separate the legends separately, make an empty storyline with geom_blank

+4
source

All Articles