如何绘制直方图,其中 y 轴表示 geom_histogram 箱中观测值的比例?
how can I plot a histogramme with y axis representing proportion of observations in a bin with geom_histogram?
我想绘制直方图,其中 y 轴显示 bin 中观测值的比例。我尝试使用此处建议的代码
https://ggplot2.tidyverse.org/reference/geom_histogram.html
ggplot(data=diamonds, aes(x=carat, after_stat(density))) + geom_histogram(binwidth = 0.05, position="identity", fill = "white", colour = "black")
这里
Normalizing y-axis in histograms in R ggplot to proportion by group
ggplot(data=diamonds, aes(x=carat)) + geom_histogram(aes(y=..density..), binwidth = 0.05, position="identity", fill = "white", colour = "black")
但是两种情况下y轴范围都大于1。
此外,当我减小 binwidth 时,y 轴的范围(即代表最多的组中的比例)变得更高,这没有任何意义,因为如果我增加组数,组大小应该会减小。
我认为这就是您要查找的内容:
ggplot(data=diamonds, aes(x=carat)) +
geom_histogram(aes(y = stat(count/sum(count))),
binwidth = 0.1, position="identity",
fill = "white", colour = "black")
这是因为直方图只是密度(或分布)的估计值,而不是为您提供每个区间中的比例。尽管连续分布函数的积分为 1,但它的高度确实可以大于 1。绘制方差递减的正态分布的密度函数以说服自己这一点。如果您希望直方图反映每个 bin 中的比例,您将必须创建一个新的分类变量,它属于哪个 bin,然后用落在该 bin 中的比例对其进行汇总。然而,我的问题是为什么你会想要这样做,或者更确切地说,为什么这是比已经给出的更好的密度总结(因为它只是密度的缩放版本并且仍然给出相对比例)?
编辑:
如果您觉得用每个箱子中的比例下降更好地解释,以下 s.o. post 有您的答案:
library(ggplot2)
data(diamonds)
ggplot(diamonds, aes(x=carat)) +
geom_histogram(aes(y=..count../sum(..count..)), binwidth=0.05)
我想绘制直方图,其中 y 轴显示 bin 中观测值的比例。我尝试使用此处建议的代码
https://ggplot2.tidyverse.org/reference/geom_histogram.html
ggplot(data=diamonds, aes(x=carat, after_stat(density))) + geom_histogram(binwidth = 0.05, position="identity", fill = "white", colour = "black")
这里
Normalizing y-axis in histograms in R ggplot to proportion by group
ggplot(data=diamonds, aes(x=carat)) + geom_histogram(aes(y=..density..), binwidth = 0.05, position="identity", fill = "white", colour = "black")
但是两种情况下y轴范围都大于1。
此外,当我减小 binwidth 时,y 轴的范围(即代表最多的组中的比例)变得更高,这没有任何意义,因为如果我增加组数,组大小应该会减小。
我认为这就是您要查找的内容:
ggplot(data=diamonds, aes(x=carat)) +
geom_histogram(aes(y = stat(count/sum(count))),
binwidth = 0.1, position="identity",
fill = "white", colour = "black")
这是因为直方图只是密度(或分布)的估计值,而不是为您提供每个区间中的比例。尽管连续分布函数的积分为 1,但它的高度确实可以大于 1。绘制方差递减的正态分布的密度函数以说服自己这一点。如果您希望直方图反映每个 bin 中的比例,您将必须创建一个新的分类变量,它属于哪个 bin,然后用落在该 bin 中的比例对其进行汇总。然而,我的问题是为什么你会想要这样做,或者更确切地说,为什么这是比已经给出的更好的密度总结(因为它只是密度的缩放版本并且仍然给出相对比例)?
编辑:
如果您觉得用每个箱子中的比例下降更好地解释,以下 s.o. post 有您的答案:
library(ggplot2)
data(diamonds)
ggplot(diamonds, aes(x=carat)) +
geom_histogram(aes(y=..count../sum(..count..)), binwidth=0.05)