无法使用facet_wrap获得geom_text标签

问题描述

我似乎无法弄清楚为什么这段代码对我不起作用。我正在尝试向此图的每个方面添加不同的geom_text标签。我为注释信息创建了一个df。

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

testParv <- data.frame(Stock = c("Birk","Dolly","Chil","Pitt","Birk","Pitt"),Parvicapsula = c("0","1","0","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),y1 = c(0.4,0.4,0.4),Stock = c("Birk",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","Pitt"),Parvicapsula = c("0","1","0","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),y1 = c(0.4,0.4,0.4),Stock = c("Birk",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,y = y1,label = lab)) +
  facet_wrap(~Stock) + 
  ylab("ECDF") 

输出:

enter image description here

,

当您在aes内设置ggplot()时,这些美感将在所有后续几何中使用。例如

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,linetype = Parvicapsula)) + 
  geom_text(data = annotest,aes(x = x1,label = lab)) +
  theme_cowplot() + 
  facet_wrap(~Stock) + 
  ylab("ECDF") 
# In geom_text overwrite the linetype with NA
ggplot(data = testParv,label = lab,linetype = NA)) +
  theme_cowplot() + 
  facet_wrap(~Stock) + 
  ylab("ECDF") 

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...