different text in each facet window [duplicate]

左心房为你撑大大i 提交于 2020-08-26 10:37:05

问题


I am trying to add median and mean values to each facet window using the following code:

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))

My main question is how to add a different text element to each facet plot, which in this example means adding median and mean for each species.

Thanks.


回答1:


Make a data frame with the values you want, and the column you facet by:

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)

Don't use sequentially named variables like mean1, mean2, mean3. Program, don't copy/paste find/replace.



来源:https://stackoverflow.com/questions/48288530/different-text-in-each-facet-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!