Building a normal curve from a histogram using ggplot2: the code produces a straight line at 0

This forum has already helped me in creating the code that I expected to return a histogram of a specific variable superimposed on its empirical normal curve. I used ggplot2 and stat_function to write code. Unfortunately, the code created a graph with the correct histogram, but the normal curve is a straight line at zero (the red line on the graph obtained by the following code).

For this minimal example, I used the mtcars dataset - the same ggplot and stat_function behavior is observed with my original dataset.

This code is written and used:

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)

I also tried specifying dnorm:

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

This did not work either - an error message appeared indicating that the arguments are not numeric.

, , , ! !

, Jannik

+4
1

, stat_function, list, . aes ggplot. (, , ), , ggplot SO.

arg stat_function 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

+11

All Articles