【问题标题】:How to plot a density curve in R using percentages?如何使用百分比在 R 中绘制密度曲线?
【发布时间】:2018-05-09 11:32:09
【问题描述】:

我不确定我所问的在概念上是否正确,主要是因为密度本身的定义,但无论如何......

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

提前致谢。

【问题讨论】:

  • 您是否需要百分号,即使用0.1% 而不是0.001,或者密度加起来不等于100% 或1.0 的问题?

标签: r ggplot2 histogram percentage density-plot


【解决方案1】:

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

【讨论】:

  • 完美,彼得。这正是我想要的!非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
相关资源
最近更新 更多