I wish to draw different density functions in the same histogram. This is one example:
CodePudding user response:
ggplot(mtcars, aes(mpg))
geom_histogram(aes(y = ..count../40),
fill = "gray70", color = "gray50")
geom_density(aes(color = "default"))
geom_density(adjust = 2, aes(color = "longer"))
geom_density(adjust = 1/2, aes(color = "shorter"))
geom_density(kernel = "epanechnikov", aes(color = "epanechnikov"))
geom_density(kernel = "rectangular", aes(color = "rectangular"))
geom_density(kernel = "cosine", aes(color = "cosine"))
CodePudding user response:
And here is a solution with plot from R base: Use plot (or hist) for the first plot and lines for subsequent plots.
Beware to use freq=FALSE
, because otherwise the histogram area is not normalized to one.
x <- rnorm(50)
hist(x, freq=F)
xx <- seq(min(x)-0.5, max(x) 0.5, 0.01)
lines(xx, dnorm(xx), col="red")
lines(density(x), col="blue")