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