【问题标题】:ggplot density function not correct (normal percent from Stata)ggplot密度函数不正确(来自Stata的正常百分比)
【发布时间】:2018-08-28 03:33:30
【问题描述】:

我正在尝试复制 hist 正常百分比。问题是密度图(或正态分布)完全关闭:

library(scales)
library(ggplot2)
a <- data.frame(rnorm(100,0,1))
colnames(a) <- c("test")
ggplot(a,aes(test)) +
geom_histogram(aes(y=(..count..)/sum(..count..))) +  
scale_y_continuous(labels=scales::percent) +
stat_function(fun='dnorm')

这条线应该更接近图表,但它被缩放了大约 10 倍。

【问题讨论】:

  • 在 Stata 中,sysuse auto, clear 后跟 hist mpg, normal percent 可能是您尝试模拟的示例。即使 Stata 语法不是 R 等价物的指南,但还是给出了 Stata 示例最重要的是,显示示例图对于明确的问题至关重要。在这种情况下,Stata 对 bin 相对频率使用百分比标度,并叠加按相同单位标度的正态分布(均值和 SD 相同)。

标签: r ggplot2 plot stata


【解决方案1】:

不熟悉来自 Stata 的命令,但这是您想要的吗?带有条形高度的密度按比例缩放,以便总面积积分为 1,就像您显示的正态曲线一样。您的尝试不起作用的原因是因为您没有考虑 bin 宽度;每个 bin 贡献的面积是宽度乘以计数。如果您设置 bin 宽度,您可以手动执行此操作,或者您可以只使用计算出的 ..density.. 变量。

library(ggplot2)
set.seed(12345)
a <- data.frame(test = rnorm(100, 0, 1))
ggplot(a, aes(x = test)) +
  geom_histogram(aes(y = ..count.. / (sum(..count..) * 0.2)), binwidth = 0.2) +
  scale_y_continuous(labels = scales::percent) +
  stat_function(fun = "dnorm")

ggplot(a, aes(x = test)) +
  geom_histogram(aes(y = ..density..), binwidth = 0.2) + 
  scale_y_continuous(labels = scales::percent) +
  stat_function(fun = "dnorm")

reprex package (v0.2.0) 于 2018 年 8 月 27 日创建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 2022-12-12
    • 2014-04-01
    • 2017-05-12
    • 1970-01-01
    • 2011-12-11
    • 2017-03-09
    • 2021-04-17
    相关资源
    最近更新 更多