r - 在ggplot2中的图例下插入表格

标签 r ggplot2

我发布了这个问题earlier但事实证明我确认的答案有问题,所以我再次发布此问题,希望能解决这个问题。

我有以下 data.frame,我想用 ggplot2 将其绘制到文件中:

df = data.frame(mean=c(1.96535,2.133604,1.99303,1.865004,2.181713,1.909511,2.047971,1.676599,2.143763,1.939875,1.816028,1.95465,2.153445,1.802517,2.141799,1.722428),
sd=c(0.0595173,0.03884202,0.0570006,0.04934336,0.04008221,0.05108064,0.0463556,0.06272475,0.04321496,0.05283728,0.05894342,0.05160038,0.04679423,0.05305525,0.04626291,0.0573123),
par=as.factor(c("p","p","m","m","p","p","m","m","m","m","p","p","m","m","p","p")),
group=as.factor(c("iF","iF","iF","iF","iM","iM","iM","iM","RF","RF","RF","RF","RM","RM","RM","RM")),
rep=c(1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2)) 

这是我用于生成 ggplot2 对象的代码:

p <- ggplot(df,aes(factor(rep),y=mean,ymin=mean-2*sd,ymax=mean+2*sd,color=factor(par)))
p <- p + geom_pointrange()+facet_wrap(~group, ncol = 4)+scale_color_manual(values = c("blue","red"),labels = c("p","m"),name = "par id")
p <- p + ggtitle("test")
p <- p + labs(y="log(y)",x="rep")

我另外想做的是将此 data.frame 添加为图例下的表格:

leg.df = data.frame(statistic = c("pp(par)","pp(g)","pp(s)","fc(p/m)"), value = c(0.96,0.94,0.78,1.5))

我得到了这个解决方案:

leg.df.grob <-  tableGrob(leg.df, gpar.coretext =gpar(fontsize=8),
         par.coltext=gpar(fontsize=8), 
         gpar.rowtext=gpar(fontsize=8))

### final result
library(gridExtra)
pp <- arrangeGrob(p + theme(legend.position = "none"), 
                  arrangeGrob(leg.df.grob, legend), ncol = 2)

然后,理论上,我可以将 pp 保存到文件中,例如使用:

ggsave('plot.png',pp)

不幸的是,命令:

pp <- arrangeGrob(p + theme(legend.position = "none"), 
                      arrangeGrob(leg.df.grob, legend), ncol = 2) 

导致绘图设备打开(这正是我想要避免的),此外它还抛出此错误:

Error in arrangeGrob(leg.df.grob, legend) : input must be grobs!

知道如何解决这个问题吗?

最佳答案

另一个解决方案是正确的。我猜您会收到错误,因为您没有设置 legend 变量。因此,使用 R 函数 legend 作为参数来调用 arrangeGrob。您应该将legend定义为:

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)
}
legend <- g_legend(p)

我稍微修改了另一个答案,通过设置 widths 参数来更好地重新排列 grobs:

pp <- arrangeGrob(p + theme(legend.position = "none"), 
                  widths=c(3/4, 1/4),
                  arrangeGrob( legend,leg.df.grob), ncol = 2)

enter image description here

关于r - 在ggplot2中的图例下插入表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20456163/

相关文章:

r - 如何为由三个子组组成的两个独立组添加图例标题?

在 ubuntu 中使用 wine 在 R 中运行 Windows 可执行文件

r - 按特定模式过滤掉字符串

r - 使用 ggplot2 创建折线图,使用时间段作为 x 变量

r - 如何在 ggplot2 中使用 facet_grid 获得适合的长标签?

r - 解释 ARIMA 模型的预测

r - 在混淆矩阵中显示决策树的结果

r - ggplot2图例到底部和水平

r - 如何使用ggplot2在甘特图中有条件地加粗y轴文本

r - 使用R在一个图形上绘制多个线段