【问题标题】:Plotting normal curve over histogram using ggplot2: Code produces straight line at 0使用 ggplot2 在直方图上绘制正态曲线:代码在 0 处产生直线
【发布时间】:2015-05-24 18:56:11
【问题描述】:

这个论坛已经为我生成代码提供了很多帮助,我希望它返回一个特定变量的直方图,上面覆盖着它的经验正态曲线。我使用 ggplot2 和 stat_function 编写代码。 不幸的是,该代码生成了具有正确直方图的图,但正态曲线是零处的直线(以下代码生成的图中的红线)。

对于这个最小的示例,我使用了 mtcars 数据集 - 在我的原始数据集上观察到了 ggplot 和 stat_function 的相同行为。

这是编写和使用的代码:

library(ggplot2)
mtcars
hist_staff <- ggplot(mtcars, aes(x = mtcars$mpg)) + 
  geom_histogram(binwidth = 2, colour = "black", aes(fill = ..count..)) +
  scale_fill_gradient("Count", low = "#DCDCDC", high = "#7C7C7C") +
  stat_function(fun = dnorm, colour = "red")
print(hist_staff)

我也尝试指定 dnorm:

stat_function(fun = dnorm(mtcars$mpg, mean = mean(mtcars$mpg), sd = sd(mtcars$mpg))

这也没有解决 - 返回一条错误消息,指出参数不是数字。

我希望你们能帮助我!提前非常感谢!

最好的,詹尼克

【问题讨论】:

  • stat_function(fun = dnorm, arg = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))
  • stat_function(fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))
  • @ManojKumar (a) cmets 属于,嗯,Comments 和 (b) 在决定对工作代码进行上述评论之前查找“r 函数参数部分匹配”。
  • 此链接提供了更好的解决方案。 stackoverflow.com/questions/5688082/…

标签: r ggplot2 histogram


【解决方案1】:

您的曲线和直方图在不同的 y 尺度上,并且您没有查看 stat_function 上的帮助页面,否则您会将参数放在 list 中,正如示例中清楚显示的那样。您也没有在最初的ggplot 通话中直接拨打aes。我真诚地建议点击更多教程和书籍(或至少帮助页面)而不是在 SO 上零碎学习 ggplot。

一旦您解决了stat_function arg 问题和ggplot``aes 问题,您需要解决y 轴比例差异。为此,您需要切换直方图的 y 以使用来自底层 stat_bin 计算数据帧的密度:

library(ggplot2)

gg <- ggplot(mtcars, aes(x=mpg))
gg <- gg + geom_histogram(binwidth=2, colour="black", 
                          aes(y=..density.., fill=..count..))
gg <- gg + scale_fill_gradient("Count", low="#DCDCDC", high="#7C7C7C")
gg <- gg + stat_function(fun=dnorm,
                         color="red",
                         args=list(mean=mean(mtcars$mpg), 
                                  sd=sd(mtcars$mpg)))

gg

【讨论】:

  • 有没有办法让红色曲线延伸到 y=0?
  • 当情节涉及多个因素时,是否有办法使这项工作发挥作用?
  • 要扩展到 y=0,您可以将 x-scale 调整到合适的值。 gg &lt;- gg + scale_x_continuous(limits = c(0, 40))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 2019-11-04
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
相关资源
最近更新 更多