Plotting normal curve over histogram using ggplot2: Code produces straight line at 0

前端 未结 1 639
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 01:55

this forum already helped me a lot for producing the code, which I expected to return a histogram of a specific variable overlayed with its empirical normal curve. I used gg

相关标签:
1条回答
  • 2020-12-06 02:52

    Your curve and histograms are on different y scales and you didn't check the help page on stat_function, otherwise you'd've put the arguments in a list as it clearly shows in the example. You also aren't doing the aes right in your initial ggplot call. I sincerely suggest hitting up more tutorials and books (or at a minimum the help pages) vs learn ggplot piecemeal on SO.

    Once you fix the stat_function arg problem and the ggplot``aes issue, you need to tackle the y axis scale difference. To do that, you'll need to switch the y for the histogram to use the density from the underlying stat_bin calculated data frame:

    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

    0 讨论(0)
提交回复
热议问题