R ggplot2:geom_text 错误(未找到对象)... aes() 冲突?

R ggplot2: geom_text error (object not found)... aes() clashing?

我只想在一些箱线图的顶部添加我在绘图外计算的 Kruskal-Wallis 测试结果。我知道我可以在同一 geom_text 行中计算 kruskal.test,但在这种情况下,我宁愿将它放在外面,因为我已经有了它。

请检查以下 MWE:

library(reshape2)
library(ggplot2)
data(iris)
iris$treatment <- rep(c("A","B"), length(iris$Species)/2)
mydf <- melt(iris, measure.vars=names(iris)[1:4])
head(mydf)
mydf$both <- factor(paste(mydf$treatment, mydf$variable, sep=' -- '), levels=(unique(paste(mydf$treatment, mydf$variable, sep=' -- '))))

##Signif levels comparing treatments per Species (regardless of variable)
addkw1 <- as.data.frame(mydf %>% group_by(Species) %>%
                       summarize(p.value = wilcox.test(value ~ treatment)$p.value)) #no need for kruskal, only 2 treatments
##Signif levels comparing variable per Species (regardless of treatment)
addkw2 <- as.data.frame(mydf %>% group_by(Species) %>%
                       summarize(p.value = kruskal.test(value ~ variable)$p.value))
##Signif levels comparing treatment+variable per Species
addkw3 <- as.data.frame(mydf %>% group_by(Species) %>%
                        summarize(p.value = kruskal.test(value ~ both)$p.value))
addkw1$TEST <- "Treatment"
addkw2$TEST <- "Variable"
addkw3$TEST <- "Treat:Var"
addkw <- rbind(addkw1, addkw2, addkw3)
addkw$p.adjust <- p.adjust(addkw$p.value, "BH")
addkw

sp <- "setosa"
addkw0 <- subset(addkw, Species==sp)
df0 <- subset(mydf, Species==sp)

pdf(file="test.df", height=15, width=15)
print(
  ggplot(df0, aes(x=both, y=value, fill=both)) + geom_boxplot() +
    stat_summary(fun.y=mean, geom="point", shape=5, size=4) +
    geom_text(data=addkw0,aes(x=0, y=0, label=p.adjust))
)
dev.off()

如您所见,我只想绘制 setosa 的箱线图,为此我有 3 个 Kruskal-Wallis p 值。我想要箱线图顶部的 3 行,例如:

KW p-value Treatment = 9.96e01
KW p-value Variable = 1.92e39
KW p-value Treat:Var = 1.18e36

但是,我收到以下错误,我不知道如何解决...我的猜测是 ggplot aes()geom_text 之间可能存在一些冲突aes().

Error in FUN(X[[i]], ...) : object 'both' not found

编辑

感谢@baptiste 的评论,我设法避免了错误,但我仍然难以打印 3 行 3 KW 值...有帮助吗?

这是新代码:

png(filename="test.png")
print(
  ggplot(df0, aes(x=both, y=value)) + geom_boxplot(aes(fill=both)) +
  stat_summary(fun.y=mean, geom="point", shape=5, size=4) +
  geom_text(data=addkw0, aes(x=0, y=0, label=paste0("KW pv = ", formatC(p.adjust, format="e", digits=2))), hjust=0)
)
dev.off()

产生这个:

要控制geom_text的位置,您需要指定每个标签的坐标。因为对于所有三个字符串,您在 geom_text 调用中指定了 x = 0y = 0,它们重叠。

ggplot(df0, aes(x = both, y = value)) + geom_boxplot(aes(fill = both)) +
  stat_summary(fun.y = mean, geom = "point", shape = 5, size = 4) +
  geom_text(data = addkw0, aes(x = 7, y = c(4.5, 5, 5.5),
                               label = paste0("KW pv = ", formatC(p.adjust, format="e", digits=2))), hjust = 0)

对于其他应用程序,例如在每个条形图顶部标记文本,需要事先计算出适当的坐标并将它们合并到对应于 addkw0.

的数据框中