如何使用百分比在 R 中绘制密度曲线?
How to plot a density curve in R using percentages?
我不确定我问的在概念上是否正确,主要是因为密度本身的定义,但无论如何...
我正在尝试在 R 中绘制密度图,但在 y 轴上使用百分比。在下图中,我成功绘制了我需要的曲线,但在我看来这并不是 y 轴上的百分比。
我用来制作它的代码如下:
ggplot(data = base_15
, aes(x = inv_hab, y = ..count../sum(..count..)
, colour = abrg_natjur)
) + geom_density()
我已经搜索了很多地方,例如:
http://www.cookbook-r.com/Graphs/Plotting_distributions_(ggplot2)/
https://en.wikipedia.org/wiki/Density_estimation
Use hist() function in R to get percentages as opposed to raw frequencies
但我还是失败了。当我使用
geom_histogram(aes(y = ..count../sum(..count..)))
有效,y 轴变为百分比,但不适用于 geom_density。我想用线而不是列来绘制它。
提前致谢。
您可以更改 geom_*
使用的 stat
以获得所需的输出。
我将在本示例中使用 ggplot2
包中的 mpg
数据集。
如您所述,
library(ggplot2)
ggplot(mpg) + aes(x = hwy, y = ..count../sum(..count..)) + geom_histogram()
以直方图形式生成所需的输出:
通过使用 stat = 'bin'
调用 geom_density
,与 geom_histogram
相同的统计数据,而不是 geom_density
的默认 stat = 'density'
你会得到什么我想你正在寻找:
ggplot(mpg) + aes(x = hwy, y = ..count../sum(..count..)) + geom_density(stat = 'bin')
我不确定我问的在概念上是否正确,主要是因为密度本身的定义,但无论如何...
我正在尝试在 R 中绘制密度图,但在 y 轴上使用百分比。在下图中,我成功绘制了我需要的曲线,但在我看来这并不是 y 轴上的百分比。
我用来制作它的代码如下:
ggplot(data = base_15
, aes(x = inv_hab, y = ..count../sum(..count..)
, colour = abrg_natjur)
) + geom_density()
我已经搜索了很多地方,例如:
http://www.cookbook-r.com/Graphs/Plotting_distributions_(ggplot2)/
https://en.wikipedia.org/wiki/Density_estimation
Use hist() function in R to get percentages as opposed to raw frequencies
但我还是失败了。当我使用
geom_histogram(aes(y = ..count../sum(..count..)))
有效,y 轴变为百分比,但不适用于 geom_density。我想用线而不是列来绘制它。
提前致谢。
您可以更改 geom_*
使用的 stat
以获得所需的输出。
我将在本示例中使用 ggplot2
包中的 mpg
数据集。
如您所述,
library(ggplot2)
ggplot(mpg) + aes(x = hwy, y = ..count../sum(..count..)) + geom_histogram()
以直方图形式生成所需的输出:
通过使用 stat = 'bin'
调用 geom_density
,与 geom_histogram
相同的统计数据,而不是 geom_density
的默认 stat = 'density'
你会得到什么我想你正在寻找:
ggplot(mpg) + aes(x = hwy, y = ..count../sum(..count..)) + geom_density(stat = 'bin')