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

时间:2017-11-13 02:00:29

标签: r testing ggplot2 geom-text

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

请检查以下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 {{之间可能存在一些冲突1}}。

  

FUN中的错误(X [[i]],...):找不到对象'两者'

修改

感谢@ baptiste的评论,我设法避免了这个错误,但我还是很难用3 KW值打印3行......有什么帮助吗?

这是新代码:

aes()

产生这个:

test

1 个答案:

答案 0 :(得分:1)

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

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)

enter image description here

对于其他应用程序,例如在每个条形图上标记文本,需要先预先计算适当的坐标,并将它们合并到与addkw0对应的数据框中。