2017-11-25 218 views
0

我不確定我所要求的概念是否正確,主要是因爲密度本身的定義,但無論如何...如何使用百分比繪製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

回答

1

您可以更改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

完美,彼得。這是我所尋找的東西!非常感謝你!! –