r - 在 “geom_signif”函数中找不到对象

标签 r ggplot2 error-handling visualization

我想添加显着性星,用于对图进行均值差比较。没有星星的线条,该图有效:

da<-data.frame(group=c("condition1_high","condition1_low","condition2_high","condition2_low"),numb=c(30,25,26,20))

da %>% separate(group, c("A", "B"), remove = F) %>% 
  ggplot(aes(x=A, y=numb, fill = B)) +
  geom_bar(position=position_dodge(), stat="identity") +
  scale_fill_manual(values=rep(c("grey20","grey80"), ceiling(length(da$group)/2))[1:length(da$group)]) +
  geom_text(aes(label=numb), 
            position = position_dodge(width = 0.9), vjust = -0.25) +
  geom_signif(stat="identity",
              data=data.frame(x=c(0.5,1.5), xend=c(1,2),
                              y=c(30, 30), annotation=c("**", "*","***","+")),
              aes(x=x,xend=xend, y=y, yend=y, annotation=annotation))
Plot without stars
现在,我为在此平台上找到的星星添加一些代码:
da %>% separate(group, c("A", "B"), remove = F) %>% 
  ggplot(aes(x=A, y=numb, fill = B)) +
  geom_bar(position=position_dodge(), stat="identity") +
  scale_fill_manual(values=rep(c("grey20","grey80"), ceiling(length(da$group)/2))[1:length(da$group)]) +
  geom_text(aes(label=numb), 
            position = position_dodge(width = 0.9), vjust = -0.25) +
  geom_signif(stat="identity",
              data=data.frame(x=c(0.5,1.5), xend=c(1,2),
                              y=c(30, 30), annotation=c("**", "*")),
              aes(x=x,xend=xend, y=y, yend=y, annotation=annotation))
现在它说对象B丢失了。我能做什么?

最佳答案

您需要将inherit.aes = FALSE添加到geom_signif调用中,否则它将尝试在您定义的新数据框中找到名为B的列。这是因为您在对aes的初始调用中放入了ggplot调用。当您执行此操作时,默认情况下,所有后续几何都将继承此调用的外观和数据。如果将新数据传递给Geom,则它需要包括所有这些美学的值或覆盖美学,或者您需要使用inherit.aes = FALSE关闭继承

da %>% 
  separate(group, c("A", "B"), remove = FALSE) %>% 
  ggplot(aes(x = A, y = numb, fill = B)) +
  geom_bar(position=position_dodge(), stat = "identity") +
  scale_fill_manual(values = rep(c("grey20", "grey80"),    
                                 ceiling(length(da$group)/2))[1:length(da$group)]) +
  geom_text(aes(label=numb), 
            position = position_dodge(width = 0.9), vjust = -0.25) +
  geom_signif(stat="identity", inherit.aes = FALSE,
              data=data.frame(x = c(0.5, 1.5), xend=c(1, 2),
                              y = c(30, 30), annotation = c("**", "*")),
              aes(x = x, xend = xend, y = y, yend = y, annotation = annotation))
enter image description here

关于r - 在 “geom_signif”函数中找不到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63034060/

相关文章:

r - smooth.Pspline stat_smooth 包装器(在 ggplot2 中)

c - libc 是否显示国际错误消息?

entity-framework - 如何将PowerShell版本从2.0升级到3.0?

r - 仅对 geom_bar 中的选定栏使用不同的颜色

r - 交互式图表中的订单栏

r - 如何忽略 _bookdown.yml 以使用自己的 YAML header 呈现章节?

r - 如何向嵌入 ggplot 图的函数添加 coord_flip 参数

ruby - Canvas LMS安装因节俭错误而失败

r - 如何抑制 R 脚本中函数的消息?

r - 如何使用 SpatialLinesDataFrame 计算行缓冲区