更改提取的图例中的标题

Change title in extracted legend

我有一个数据框:

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

我想从情节中提取图例并通过 "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)

我的问题是:在将图例添加到另一个图之前,如何将图例的标题从 "Diameter" 更改为“F49 直径”(请参阅​​附图)?

如果我没理解错的话,你只需要将 "F49 Diameter" 添加到 scale_fill_gradient

所以你的代码看起来像这样

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

还有你提取的图例

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

将命名为"F49 Diameter"