首页 > 解决方案 > 无法使用 facet_wrap 获得 geom_text 标签

问题描述

我似乎无法弄清楚为什么这段代码对我不起作用。我正在尝试向该图的每个方面添加不同的 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() 代码时它工作正常。

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

非常感谢,朱莉娅

标签: rggplot2facetgeom-text

解决方案


当您设置aesinsideggplot()调用时,这些美学将在所有后续几何中使用。例如

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

在你的情况下linetype,从一开始aes就是被带入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") 


推荐阅读