Reputation: 51
Task that I need to accomplish: 1. draw x=data/y=density histogram - done 2. draw distribution curve for given dataset - done 3. draw perfect normal distribution curve for this dataset (red line) - problem I assume problem is in 2nd stat_function.
Code is run-able w/o any preparations:
data <- data.frame(c(runif(30,1,50)),c(runif(30,50,1)))
g.data <- data[,1]
graph <- ggplot(data, aes(g.data))
graph <- graph +
geom_histogram(aes(y = ..density..), binwidth = 2, fill = 'pink') +
labs(x = 'Data', y ='Density') +
stat_function(fun = dnorm, args = list(mean = mean(g.data, na.rm = T),
sd = sd(g.data, na.rm =T)), colour ='black', size =1) +
theme(legend.position = 'none') +
stat_function(fun = dnorm, colour = "red", args = list(mean = mean(g.data)))
graph
Here what I get
Here what I approximately need, perfect norm. distribution
Upvotes: 2
Views: 7664
Reputation: 1237
A normal distribution has 2 parameters: its mean and standard deviation. Here your provide only the mean to dnorm, so it assumes sd = 1
.
A corrected version of the code you provide is:
data <- data.frame(c(runif(30,1,50)))
ggplot(data, aes(data[,1])) +
geom_histogram(aes(y = ..density..), binwidth = 2, fill = 'pink') +
labs(x = 'Data', y = 'Density') +
stat_function(fun = dnorm,
args = list(mean = mean(data[,1], na.rm = TRUE),
sd = sd(data[,1], na.rm = TRUE)),
colour = 'black', size = 1)
Upvotes: 4