每个方面窗口中的不同文本

时间:2018-01-16 19:30:27

标签: r text ggplot2 facet

我正在尝试使用以下代码为每个构面窗口添加中值和平均值:

library(dplyr)
library(ggplot2)
data(iris)

setosa     <- filter(iris, Species == "setosa")
versicolor <- filter(iris, Species == "versicolor")
virginica  <- filter(iris, Species == "virginica")
median1    <- round(median(setosa$Sepal.Length), 1)
mean1      <- round(mean(setosa$Sepal.Length), 1)
median2    <- round(median(versicolor$Sepal.Length), 1)
mean2      <- round(mean(versicolor$Sepal.Length), 1)
median3    <- round(median(virginica$Sepal.Length), 1)
mean3      <- round(mean(virginica$Sepal.Length), 1)

print(ggplot(data = iris) +
        geom_histogram(aes(x = Sepal.Length, y = ..density..)) +
        facet_wrap(~ Species) +
        geom_text(aes(x = 6.7, y = 1.3),
                  label = noquote("median = \nmean = "),
                  hjust = 0))

enter image description here 我的主要问题是如何为每个构面图添加不同的文本元素,在本例中,这意味着为每个物种添加中值和均值。

感谢。

1 个答案:

答案 0 :(得分:2)

创建一个包含所需值的数据框,以及您所代表的列:

iris_summary = iris %>% group_by(Species) %>%
  summarize(median = median(Sepal.Length),
            mean = mean(Sepal.Length)) %>%
  mutate(lab = paste("median = ", median, "\nmean = ", mean))


ggplot(data = iris) +
        geom_histogram(aes(x = Sepal.Length, y = ..density..)) +
        facet_wrap(~ Species) +
        geom_text(data = iris_summary, aes(label = lab), x = 6.7, y = 1.3)

enter image description here

请勿使用顺序命名的变量,例如mean1mean2mean3。编程,不要复制/粘贴查找/替换。