【问题标题】:Adding a title to a legendGrob为 legendGrob 添加标题
【发布时间】:2019-03-20 18:57:00
【问题描述】:

我的 ggplots 没有自己的图例,因为我的 ggplots 是迭代更新的。无论如何我想要一个整体图例,所以我使用以下代码:

grid.arrange(
 arrangeGrob(grobs=plot,ncol=2,left=textGrob(colnames(data)[i],rot=90),
  bottom=legendGrob(labels=colnames(data [other_cors[,1]],pch=other_cors[,1],
  ncol=length(others),gp=gpar(col=other_cors[,1],cex=0.9)),
  right=legendGrob(labels=other_cors[,2],pch=15,nrow=length(others),
  gp=gpar(col=other_cors[,1],cex=0.9)),top=textGrob(paste("Associations with ",
  colnames(data)[i],sep=""),gp=gpar(fontface="bold"))
 )
)

这样的情节是:multiple ggplot

我的问题是我不知道如何为右侧创建的图例添加标题。有没有办法可以在红色方块和 0.83 线上方添加一个字符串?或者有没有办法在同一侧拥有两个 Grob,例如 textGrob 和 legendGrob?

我希望它看起来像这样:Ideal plot

如有必要,以下是创建我的 ggplots 的代码:

others = 1:NCOL(my_bones)
others = others[-i]
plot=list()
for (k in 1:2){
if (k==1){
data = my_bones
title = "Raw"
} else {
data = standard_bones
title = "Standardized"
}
for (j in others){
 if (j==min(others)){
  plot[[k]] = ggplot(data=data,mapping=aes(x=data[,others],y=data[,i]))+
    geom_point(x=data[,j],y=data[,i],col=j,shape=j,cex=3)+
    theme_test()+ labs(title=title)+
    theme(axis.title.x=element_blank(),
          axis.ticks.x=element_blank(),
          axis.title.y=element_blank(),
          axis.ticks.y=element_blank())+
    xlim(range(data[,others]))+
    ylim(range(data[,i]))
 } else {
  plot[[k]] = plot[[k]]+ 
    geom_point(x=data[,j],y=data[,i],col=j,shape=j,cex=3)
 }
 model = colnames(data)
 model = paste("`",model[i],"`","~","`",model[j],"`",sep="")
 model = lm(as.formula(model),data=data)
 beta = summary(model) 
 beta = beta$coefficients 
 beta = beta[,1] 
 plot[[k]] = plot[[k]]+
   geom_abline(intercept=beta[1],slope=beta[2],col=j,cex=1)
 }
}
other_cors = cbind(others,round(cors[others,i],2))
other_cors = other_cors[order(other_cors[,2],decreasing=T),]

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    通过为每个单独的情节添加图例标题,我得到了类似的工作。所以如果你添加

     + labs(col = "legend title",
            shape = "legend title"
            )
    

    它应该工作。只要您在每个情节中映射的每种美学都有相同的标签,grid.arrange() 应该添加一个图例标题

    【讨论】:

    • 感谢您的回答。我知道从个别情节中获取传说是可能的。我试图从头开始创建一个图例,因为我无法让缩放功能按我想要的方式工作,但我找到了一个快速而肮脏的解决方案:添加“标题”作为第一个标签,然后更改第一个颜色(如果你正在使用颜色)来匹配背景。
    猜你喜欢
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多