本文介绍了每个方面窗口中的不同文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码将中值和均值添加到每个构面窗口:
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.
谢谢.
推荐答案
使数据框具有所需的值以及包含以下内容的列:
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)
请勿使用顺序命名的变量,例如mean1
,mean2
,mean3
.编程,请勿复制/粘贴查找/替换.
Don't use sequentially named variables like mean1
, mean2
, mean3
. Program, don't copy/paste find/replace.
这篇关于每个方面窗口中的不同文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!