简体   繁体   English

在提取的图例中更改标题

[英]Change title in extracted legend

在此处输入图片说明 I 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". 我想从剧情中提取图例,然后通过“ 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? 我的问题是:在将图例添加到另一个绘图之前,如何将图例的标题从“直径”更改为“ F49直径”(请参见随附的图片)?

If I've understood you correctly, than you just need to add the "F49 Diameter" into scale_fill_gradient 如果我理解正确的你,比你只需要到“F49直径”添加到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" 将被命名为“ F49直径”

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM