无法使用 facet_wrap 的 geom_text 标签工作

Cannot get geom_text labels with facet_wrap to work

我似乎不明白为什么这段代码对我不起作用。我正在尝试向该图的每个方面添加不同的 geom_text 标签。我已经为注释信息创建了一个df。

这是我的数据集和代码的示例:

testParv <- data.frame(Stock = c("Birk","Dolly","Chil", "Pitt", "Birk","Dolly","Chil", "Pitt", "Birk","Dolly","Chil", "Pitt"), Parvicapsula = c("0", "1", "0", "1", "1", "0","0", "1", "0", "1", "1", "0"), Weight = c("19.2", "10.1", "5.2", "10.9", "20.5", "4.3", "15", "24", "6", "3", "8", "4.5"))

annotest <- data.frame(x1 = c(35, 35, 35, 35), y1 = c(0.4, 0.4, 0.4, 0.4), Stock = c("Birk", "Chil", "Dolly", "Pitt"), lab = c("p = 0.968", "p = 0.384", "p = 0.057", "p = 0.005"))

ggplot(data = testParv, aes(x = Weight, linetype = Parvicapsula)) +
  stat_ecdf() + 
  geom_text(data = annotest, aes(x = x1, y = y1, label = lab)) +
  theme_cowplot() + 
  facet_wrap(~Stock) + 
  ylab("ECDF") 

这会产生错误:FUN(X[[i]], ...) 错误:找不到对象 'Parvicapsula',但是当我取出 geom_text() 代码时工作正常。

有谁知道为什么这不起作用?

非常感谢, 茱莉亚

我建议采用下一种方法。我对标签坐标做了细微的改动。问题是,如果将 geom_text() 与其他数据框一起使用,则必须注意初始 aes 中数据框中的所有变量也在标签数据框中。这里的代码:

library(ggplot2)
#Data
testParv <- data.frame(Stock = c("Birk","Dolly","Chil", "Pitt", "Birk","Dolly",
                                 "Chil", "Pitt", "Birk","Dolly","Chil", "Pitt"),
                       Parvicapsula = c("0", "1", "0", "1", "1", "0","0", "1", "0", "1", "1", "0"),
                       Weight = c("19.2", "10.1", "5.2", "10.9", "20.5", "4.3",
                                  "15", "24", "6", "3", "8", "4.5")
                       )
#Labels
annotest <- data.frame(Weight = c(6, 6, 6, 6),
                       y1 = c(0.4, 0.4, 0.4, 0.4),
                       Stock = c("Birk", "Chil", "Dolly", "Pitt"),
                       lab = c("p = 0.968", "p = 0.384", "p = 0.057", "p = 0.005"),
                       Parvicapsula=NA)
#Plot
ggplot(data = testParv, aes(x = Weight, linetype = Parvicapsula)) +
  stat_ecdf() + 
  geom_text(data = annotest, aes(x = Weight, y = y1, label = lab)) +
  facet_wrap(~Stock) + 
  ylab("ECDF") 

输出:

当您在 ggplot() 调用中设置 aes 时,这些美学将用于所有后续的 geom。例如

ggplot(mtcars, aes(hp, mpg)) + geom_point() + geom_line()

在你的情况下,第一个 aeslinetype 被带入 geom_text。修复错误的几种不同方法。这里有两个选项:

# Move the data and aes calls into stat_ecdf 
ggplot() +
  stat_ecdf(data = testParv, aes(x = Weight, linetype = Parvicapsula)) + 
  geom_text(data = annotest, aes(x = x1, y = y1, label = lab)) +
  theme_cowplot() + 
  facet_wrap(~Stock) + 
  ylab("ECDF") 
# In geom_text overwrite the linetype with NA
ggplot(data = testParv, aes(x = Weight, linetype = Parvicapsula)) +
  stat_ecdf() + 
  geom_text(data = annotest, aes(x = x1, y = y1, label = lab, linetype = NA)) +
  theme_cowplot() + 
  facet_wrap(~Stock) + 
  ylab("ECDF")