ggplot2:为 geom_freqpoly 产生的平均计数值添加行
ggplot2: add line for average count values resulting from geom_freqpoly
我想在我的 geom_freqpoly 图中添加一条额外的线,表示每个 binwidth 的平均计数。我尝试了两种不同的方法,但 none 成功了。
- 我尝试将此行添加为 geom_line,但出现错误,询问我是否将我的统计信息映射到错误的图层。
library(tidyverse)
iris %>%
ggplot(aes(x = Petal.Length, y = ..count..)) +
geom_freqpoly(aes(color = Species),
binwidth = 0.2) +
geom_line(aes(yintercept = "mean"))
#> Warning: Ignoring unknown aesthetics: yintercept
#> Error: Aesthetics must be valid computed stats. Problematic aesthetic(s): y = ..count...
#> Did you map your stat in the wrong layer?
- 我尝试添加另一个 geom_freqpoly,例如:
library(tidyverse)
iris %>%
ggplot() +
geom_freqpoly(aes(x = Petal.Length, y = ..count.., color = Species),
binwidth = 0.2) +
geom_freqpoly(aes(x = Petal.Length, y = mean(..count..), color = "red"), binwidth = 0.2)
但是生成的行不是我所期望的。
使用 Iris 数据集,我希望新行将代表定义的 binwidth 的物种平均数(见下图),而不是我得到的。我的理解是 geom_freqpoly 将连续变量(如 Petal.Length)分成长度 bin(在本例中为 0.2 长度)。因此,对于每个箱子,我想获得每个物种的平均数量,并画一条连接这些点的线。
由 reprex package (v0.3.0)
于 2020-05-23 创建
根据您对问题的编辑,这可能是您所期望的。
您的方法的问题在于 mean(..count..)
只是计算向量 ..count..
的平均值,它给您一个数字,因此是一条水平线。因此,只需除以 groups
或 Species
的数量
我对我的解决方案并不完全满意,因为我想避免代码 n_distinct(iris$Species)
。我用 tapply
尝试了一些方法但失败了。所以作为第一步...
library(tidyverse)
ggplot(iris, aes(x = Petal.Length)) +
geom_freqpoly(aes(color = Species), binwidth = .2) +
geom_freqpoly(aes(y = ..count.. / n_distinct(iris$Species)), color = "red", binwidth = .2)
由 reprex package (v0.3.0)
于 2020-05-28 创建
我想在我的 geom_freqpoly 图中添加一条额外的线,表示每个 binwidth 的平均计数。我尝试了两种不同的方法,但 none 成功了。
- 我尝试将此行添加为 geom_line,但出现错误,询问我是否将我的统计信息映射到错误的图层。
library(tidyverse)
iris %>%
ggplot(aes(x = Petal.Length, y = ..count..)) +
geom_freqpoly(aes(color = Species),
binwidth = 0.2) +
geom_line(aes(yintercept = "mean"))
#> Warning: Ignoring unknown aesthetics: yintercept
#> Error: Aesthetics must be valid computed stats. Problematic aesthetic(s): y = ..count...
#> Did you map your stat in the wrong layer?
- 我尝试添加另一个 geom_freqpoly,例如:
library(tidyverse)
iris %>%
ggplot() +
geom_freqpoly(aes(x = Petal.Length, y = ..count.., color = Species),
binwidth = 0.2) +
geom_freqpoly(aes(x = Petal.Length, y = mean(..count..), color = "red"), binwidth = 0.2)
但是生成的行不是我所期望的。
使用 Iris 数据集,我希望新行将代表定义的 binwidth 的物种平均数(见下图),而不是我得到的。我的理解是 geom_freqpoly 将连续变量(如 Petal.Length)分成长度 bin(在本例中为 0.2 长度)。因此,对于每个箱子,我想获得每个物种的平均数量,并画一条连接这些点的线。
由 reprex package (v0.3.0)
于 2020-05-23 创建根据您对问题的编辑,这可能是您所期望的。
您的方法的问题在于 mean(..count..)
只是计算向量 ..count..
的平均值,它给您一个数字,因此是一条水平线。因此,只需除以 groups
或 Species
我对我的解决方案并不完全满意,因为我想避免代码 n_distinct(iris$Species)
。我用 tapply
尝试了一些方法但失败了。所以作为第一步...
library(tidyverse)
ggplot(iris, aes(x = Petal.Length)) +
geom_freqpoly(aes(color = Species), binwidth = .2) +
geom_freqpoly(aes(y = ..count.. / n_distinct(iris$Species)), color = "red", binwidth = .2)
由 reprex package (v0.3.0)
于 2020-05-28 创建