Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: histogram with normal curve

Tags:

r

ggplot2

curve

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)

like image 871
Bloomy Avatar asked Aug 06 '11 15:08

Bloomy


People also ask

How do I add a normal distribution curve to a histogram in R?

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.

Can you build a histogram using ggplot2?

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.

How do I create a normal curve in Ggplot with specific means and SD?

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.


1 Answers

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))) 

enter image description here

like image 158
Carlos Eduardo Vazquez Avatar answered Oct 01 '22 03:10

Carlos Eduardo Vazquez