lundi 28 avril 2014

Plot different distributions over histogram with ggplot


Vote count:

0




I was trying to plot a histogram in R and overlay it with densities from different distributions. It worked well for the regular histogram, but I can't get it to work with the ggplot2 package.


This is the code for the regular plot:



a <- dataset$age


Now follows the code for my regular histogram:



Histogram_for_age <- hist(a, prob=T, xlim=c(0,80), ylim=c(0,0.055), main="Histogram for age with density lines", xlab="TV_Alter")

mean <- mean(a)
sd <- sd(a)


And now the lines/curves for the densities:



lines(density(dataset$age), col="blue", lwd=2, lty=1)
curve(dnorm(x, mean = mean, sd = sd), add = T, col="red", lwd=2, lty=2)
curve(dgamma(x, shape =mean^2/sd^2, scale = sd^2/mean), add = T, col="goldenrod", lwd=2, lty=3)
legend("topright",
c("actual distribution of age","gaussian distribution", "gamma distribution"),
lty=c(1,2,3),
lwd=c(2,2,2),col=c("blue","red","goldenrod"), cex=0.65)


This is what I tried with ggplot2 so far:



ggplot(dataset_with_victims, aes(x=TV_Alter)) +
geom_histogram(aes(y=..density..),
colour="black", fill="white") +
geom_density(alpha=.2, fill="lightblue") + stat_function(fun = dgamma, shape=shape)


What ggplot2 argument is equivalent to my lines() and curve() arguments?



asked 36 secs ago






Aucun commentaire:

Enregistrer un commentaire