Search code examples
rggplot2extractlegendr-grid

Change title in extracted legend


enter image description hereI have a data frame:

df1 = data.frame(Time = rep(0.5:9.5, each = 10), RoiID = rep(1:10, 10), Diameter = runif(100, 5.0, 7.5),Time.hours=rep(c(1,2)))

I want to extract the legend from the plot and put to another plot by "grid.arrange".

p1=ggplot(data=subset(df1,df1$Time.hours==1), aes(x=factor(RoiID), y=Time, fill = Diameter)) + 
theme_minimal()  + coord_fixed(ratio=1/2) + 
geom_tile(colour = NA, width =1.5 , height = 1)+
scale_fill_gradient(low="black",high="white",limits=c(min(df1$Diameter),max(df1$Diameter)))+ 
theme(legend.direction="horizontal")

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

grobs <- ggplotGrob(p1 + theme(legend.position="right"))$grobs
mylegend <- grobs[[which(sapply(grobs, function(x) x$name) == "guide-box")]]
mylegend<-g_legend(p1)

My question is: How to change the title of legend from "Diameter" to " F49 Diameter" (please see image enclosed) before adding the legend to another plot?


Solution

  • If I've understood you correctly, than you just need to add the "F49 Diameter" into scale_fill_gradient

    So your code looks like this

    p1=ggplot(data=subset(df1,df1$Time.hours==1), aes(x=factor(RoiID), y=Time, fill = Diameter)) + 
      theme_minimal()  + coord_fixed(ratio=1/2) + 
      geom_tile(colour = NA, width =1.5 , height = 1)+
      scale_fill_gradient("F49 Diameter",low="black",high="white",limits=c(min(df1$Diameter),max(df1$Diameter)))+ 
      theme(legend.direction="horizontal") 
    

    And than also your extracted legend

    library(gridExtra)
    grid.arrange(g_legend(p1))
    

    will be named "F49 Diameter"

    enter image description here