在提取的图例中更改标题

时间:2017-03-30 15:30:15

标签: r ggplot2 extract legend r-grid

enter image description here我有一个数据框:

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)

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

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你需要将“F49直径”添加到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”

enter image description here