I've been trying to superimpose a normal curve over my histogram with ggplot 2.
My formula:
data <- read.csv (path...) ggplot(data, aes(V2)) + geom_histogram(alpha=0.3, fill='white', colour='black', binwidth=.04)
I tried several things:
+ stat_function(fun=dnorm)
....didn't change anything
+ stat_density(geom = "line", colour = "red")
...gave me a straight red line on the x-axis.
+ geom_density()
doesn't work for me because I want to keep my frequency values on the y-axis, and want no density values.
Any suggestions?
Thanks in advance for any tips!
Solution found!
+geom_density(aes(y=0.045*..count..), colour="black", adjust=4)
A basic histogram can be created with the hist function. In order to add a normal curve or the density line you will need to create a density histogram setting prob = TRUE as argument.
You can also make histograms by using ggplot2 , “a plotting system for R, based on the grammar of graphics” that was created by Hadley Wickham. This post will focus on making a Histogram With ggplot2.
In order to create a normal curve, we create a ggplot base layer that has an x-axis range from -4 to 4 (or whatever range you want!), and assign the x-value aesthetic to this range ( aes(x = x) ). We then add the stat_function option and add dnorm to the function argument to make it a normal curve.
Think I got it:
set.seed(1) df <- data.frame(PF = 10*rnorm(1000)) ggplot(df, aes(x = PF)) + geom_histogram(aes(y =..density..), breaks = seq(-50, 50, by = 10), colour = "black", fill = "white") + stat_function(fun = dnorm, args = list(mean = mean(df$PF), sd = sd(df$PF)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With