【问题标题】:Density values of histogram in ggplot2?ggplot2中直方图的密度值?
【发布时间】:2021-09-17 19:06:47
【问题描述】:

在基数 R 中,我们可以使用函数 hist() 来创建给定变量的密度直方图,例如 x。如果我们写:

  h <- hist(x, freq=FALSE)

那么,h$mids 是包含每个 bin 的中点值的向量,h$density 包含每个 bin 的密度。我想用 ggplot2geom_histogram() 绘制我的密度直方图。

有没有办法从 ggplot2 函数中检索相似的值(每个 bin 的中点和密度)?

【问题讨论】:

  • geom_density()怎么样?
  • 您还可以通过geom_histogram(aes(y=..density..)) 更改直方图上的比例以提供密度值(而不是默认的“计数”)。
  • 感谢您的 cmets。它只是生成一个密度直方图。我的问题是如何使用 ggplot2 函数检索每个 bin 的中点和每个 bin 的密度值。

标签: r ggplot2 graphics histogram density-plot


【解决方案1】:

您可以通过使用ggplot() + geom_histogram() 创建直方图来完成此操作,然后使用ggplot_build() 提取 bin 中点、最小值和最大值、密度、计数等。

这是一个使用内置 iris 数据集的简单示例:

library(ggplot2)

# make a histogram using the iris dataset and ggplot()
h <- ggplot(data = iris) +
  geom_histogram(mapping = aes(x=Petal.Width),
                 bins = 11)

# extract the histogram's underlying features using ggplot_build()
vals <- ggplot_build(h)$data[[1]]

# print the bin midpoints
vals$x
## 0.00 0.24 0.48 0.72 0.96 1.20 1.44 1.68 1.92 2.16 2.40

# print the bin densities
vals$density
## 0.1388889 1.0000000 0.2500000 0.0000000 0.1944444 0.5833333 0.5555556 0.5000000 0.3055556 0.2500000 0.3888889

【讨论】:

  • 非常感谢您的回答。这很有帮助。我还可以通过使用 R 函数密度()来管理这种情况。对于上面的例子,我们可以写成 d
猜你喜欢
  • 1970-01-01
  • 2014-01-30
  • 2020-06-12
  • 2022-01-17
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
相关资源
最近更新 更多