在 ggplot2 条形图中显示显着性关系

Showing significance relationships in a ggplot2 bar graph

尽管我要问的基本问题已在至少一个 previous post, the method described there has not worked for me, nor has the proposed solution, discussed here.

中得到解决

作为参考,我正在尝试使用 R 中的 ggplot2 重新创建图形 linked here

这是我使用的数据框的简化版本:

 df <-data.frame(
  Related = c("Rel","Rel","Unrel","Unrel"),
  Integrated = c("Integ", "Unint", "Integ", "Unint"),
  Rate = c(11,8,6,4),
  SE = c(1.5,1.4,1.3,1.2))

就条形图、SE 错误条形图、轴和一般格式而言,我基本上已经使用以下内容完成了到目前为止我需要的内容(不过,请注意我正在处理 x 轴标签并分别报告 p 值):

dodge <- position_dodge(width = 0.9)
g1    <- ggplot(data = df, aes(x = interaction(Integrated, Related), y     = Rate, fill = interaction(Integrated, Related))) 
g1    <- g1 + layer(geom="bar", stat="identity", position = position_dodge())
g1    <- g1 + scale_fill_manual(values=c("#990000", "#CC6666", "#000099", "#9999CC"))
g1    <- g1 + guides(fill=FALSE)
g1    <- g1 + geom_errorbar(aes(ymax = Rate + SE, ymin = Rate - SE), position = dodge, width = 0.2) 
g1    <- g1 + coord_cartesian(ylim = c(0, 15))
g1    <- g1 + scale_y_continuous(breaks=seq(0, 14, 2))
g1    <- g1 + theme_classic()
g1    <- g1 + theme(text = element_text(size=20))
g1    <- g1 + ylab("Mismatch effect (%)")
g1    <- g1 + theme(axis.title.y=element_text(vjust=1.5))
g1    <- g1 + theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
                axis.title.x = element_blank(),
                axis.text.x = element_blank())

问题是 当我尝试添加图中顶部显示的重要性 comparisons/relationship 条 时。当我尝试使用以下代码仅添加星号和顶部栏(没有第二层分支)时,它 returns 下面列出的错误并仅在适当的位置显示星号。

代码:

 g1 + geom_path(x=c(1.5,1.5,3.5,3.5),y=c(13,14,14,13))+  annotate("text",x=2.5,y=15,label="*")

错误:

geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?

在研究了问题的潜在来源(例如上面链接的 post)之后,我尝试创建一个单独的 df 并明确引用如下:

代码:

data2 <- data.frame(x = c(1.5, 1.5, 3.5, 3.5), y = c(13, 14, 14, 13))
g1 + geom_path(data = data2, aes(x = x, y = y))

但是,我再次收到一个错误:

错误:

Error in interaction(Integrated, Related) : object 'Integrated' not found

我花了很多时间试图解决这个问题,但无济于事。我很想能够重新创建上面着墨的图像。我真的很感谢任何帮助。

geom_path 需要一个分组变量。由于没有组,您需要添加 aes(group=1):

g1 + geom_path(aes(group=1), x=c(1.5,1.5,3.5,3.5), y=c(13,14,14,13)) +  
  annotate("text", x=2.5,y=14.4,label="*", size=8)

第二个错误,object 'Integrated' not found,是因为您的第二个数据集需要与原始数据集具有相同的美学和分面变量,即使您没有明确地将它们用于该层阴谋。例如,这将起作用:

data2 <- data.frame(x = c(1.5, 1.5, 3.5, 3.5), y = c(13, 14, 14, 13),
                    Integrated=NA, Related=NA)
g1 + geom_path(data = data2, aes(x = x, y = y))

我希望有用的其他一些评论:

1) 不需要每次添加新语句时都保存g1。您可以在每个语句末尾使用 + 在单个命令中将它们全部串在一起:

g1 <- ggplot(data = mis.eff, aes(x = interaction(Integrated, Related), 
             y = Rate, fill = interaction(Integrated, Related))) + 
       layer(geom="bar", stat="identity", position = position_dodge()) +
       scale_fill_manual(values=c("#990000", "#CC6666", "#000099", "#9999CC")) +
       ... etc.

2) 在您的注释中,您设置了 y=15,它位于绘图的 y 范围之上,因此它不会出现。我已将值更改为 14.4。如果你想更改它们,你也可以手动设置 y 限制。

3) 我增加了星号的大小,使其更加突出。您当然可以根据需要进行调整。