如何使用百分比绘制R中的密度曲线?

问题描述:

我不确定我所要求的概念是否正确,主要是因为密度本身的定义,但无论如何...如何使用百分比绘制R中的密度曲线?

我试图在R中绘制密度图,但在百分比中使用百分比y轴。在下面的图片中,我成功绘制了我需要的曲线,但在我看来,这并不是y轴上的百分比。

enter image description here

我用使它的代码如下:

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。我想用线条而不是列来绘制它。

在此先感谢。

+0

您是否需要百分比符号,即使用'0.1%'而不是'0.001',还是密度不加上100%或1.0的问题? – Heikki

您可以更改geom_*所使用的stat以获得所需的输出。

在本例中,我将使用ggplot2包中的mpg数据集。

正如你提到的,

library(ggplot2) 
ggplot(mpg) + aes(x = hwy, y = ..count../sum(..count..)) + geom_histogram() 

得到想要的输出直方图: enter image description here

通过调用geom_densitystat = 'bin',同样的统计作为geom_histogram,而不是默认的stat = 'density'geom_density你会得到我认为你正在寻找的东西:

ggplot(mpg) + aes(x = hwy, y = ..count../sum(..count..)) + geom_density(stat = 'bin') 

enter image description here

+0

完美,彼得。这是我所寻找的东西!非常感谢你!! –