首页 文章

使用ggplot2在直方图上绘制正态曲线:代码在0处产生直线

提问于
浏览
8

这个论坛已经帮助我制作了很多代码,我希望这些代码能够返回一个特定变量的直方图,该变量与其经验正态曲线重叠 . 我使用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))

这也没有用 - 返回一条错误消息,声明参数不是数字 .

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

最好的,Jannik

1 回答

  • 18

    你的曲线和直方图是在不同的y尺度上,你没有检查 stat_function 上的帮助页面,否则你'd'已将参数放在 list 中,因为它在示例中清楚地显示 . 你也没有在最初的 ggplot 电话中做 aes . 我真诚地建议更多的教程和书籍(或者至少是帮助页面)与学习ggplot零碎的SO .

    一旦修复 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
    

    enter image description here

相关问题