指定组时,在ggplot2中使用facet_wrap的geom_text

时间:2015-12-30 18:59:16

标签: r ggplot2

当使用ggplot2制作分面图时,我在指定分组参数时无法在每个构面中获取单个标签。没有指定group = ...,事情就可以了,但是我试图制作强调治疗前和治疗后变化的配对数据图。

以下是一个例子:

library(tidyr)
library(ggplot2)

set.seed(253)
data <- data.frame(Subject = LETTERS[1:10],
                   Day1.CompoundA = rnorm(10, 4, 2),
                   Day2.CompoundA = rnorm(10, 7, 2),
                   Day1.CompoundB = rnorm(10, 5, 2),
                   Day2.CompoundB = rnorm(10, 5.5, 2))

# Compare concentration of compounds by day
A <- t.test(data$Day1.CompoundA, data$Day2.CompoundA, paired = TRUE)
B <- t.test(data$Day1.CompoundB, data$Day2.CompoundB, paired = TRUE)

data.long <- gather(data, key = DayCompound, value = Concentration, -Subject) %>%
      separate(DayCompound, c("Day", "Compound"))

# text to annotate graphs
graphLabels <- data.frame(Compound = c("CompoundA", "CompoundB"),
                          Pval = paste("p =", c(signif(A$p.value, 2), 
                                                signif(B$p.value, 2))))

好的,现在数据已经设置完毕,我可以制作一个箱形图:

ggplot(data.long, aes(x = Day, y = Concentration)) +
      geom_boxplot() +
      facet_wrap(~ Compound) +
      geom_text(data = graphLabels, aes(x = 1.5, y = 10, label = Pval))

boxplot example

但是,如果我想通过以不同颜色显示每个主题来显示强调数据配对性质的线条图,则方面标签不起作用。

ggplot(data.long, aes(x = Day, y = Concentration, color = Subject, group = Subject)) +
      geom_point() + geom_line() +
      facet_wrap(~ Compound) +
      geom_text(data = graphLabels, aes(x = 1.5, y = 10, label = Pval))

# Error in eval(expr, envir, enclos) : object 'Subject' not found

有什么建议吗?

1 个答案:

答案 0 :(得分:12)

当您在顶级aes(...,color = Subject)调用中映射美学(即ggplot())时,这些映射会传递到每个图层,这意味着每个图层都希望数据具有这些名称的变量。 / p>

您需要在每个图层中单独指定数据和映射,或者明确取消映射它们:

ggplot(data.long, aes(x = Day, y = Concentration, color = Subject, group = Subject)) +
    geom_point() + geom_line() +
    facet_wrap(~ Compound) +
    geom_text(data = graphLabels, aes(x = 1.5, y = 10, label = Pval,color = NULL,group= NULL))

还有一个inherit.aes参数,您可以在任何不想要引入其他映射的图层中将其设置为FALSE,例如

ggplot(data.long, aes(x = Day, y = Concentration, color = Subject, group = Subject)) +
    geom_point() + geom_line() +
    facet_wrap(~ Compound) +
    geom_text(data = graphLabels, aes(x = 1.5, y = 10, label = Pval),inherit.aes = FALSE)