ggplot: plotting more than one function on one plot

Viewed 151

I have a task to plot histogram using my data (here) named NoPodsWeight, its density and normal distribution for this segment (min(NoPodsWeight) and max(NoPodsWeight)).
I am trying this:

myframe <- read.csv(filepath, fileEncoding = "UTF-8", stringsAsFactors = FALSE)
myframe <- myframe[rowSums(is.na(myframe)) <= 0,]
nopodsweight <- myframe$NoPodsWeight
height <- myframe$Height
ggplot(myframe, aes(x = NoPodsWeight, y = ..density..)) + 
   geom_histogram(color="black", fill="white") + 
   geom_density(color = "blue") +
   stat_function(fun = dnorm, args = list(mean = mean(myframe$NoPodsWeight), sd = sd(myframe$NoPodsWeight)))

Using this code I get an error:

Error: Aesthetics must be valid computed stats. Problematic aesthetic(s): y = ..density... Did you map your stat in the wrong layer?

I don't understand how to plot two or more functions on one plot. For example I can solve my problem using standard plot (but without density):

 hist(x = nopodsweight, freq = F, ylim = c(0, 0.45), breaks = 37)
 n_norm<-seq(min(nopodsweight)-1, max(nopodsweight)+1, 0.0001)
 lines(n_norm, dnorm(n_norm), col = "red")

enter image description here

Is there any function in ggplot to plot (normal) distribution (or maybe using another function) like in lines?

2 Answers

You need to take ..density.. out of the ggplot() layer and put it specifically in the geom_histogram layer. I didn't download and import your data, but here's an example on mtcars:

ggplot(mtcars, aes(x = mpg)) +
  geom_histogram(aes(y = ..density..)) +
  geom_density(color = "blue") +
  stat_function(fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))

enter image description here

The error message says "did you map your stat in the wrong layer?"; that's a hint. Moving aes(y=..density..) to apply specifically to geom_histogram() seems to make everything OK ...

ggplot(myframe, aes(x = NoPodsWeight)) + 
    geom_histogram(color="black", fill="white",
                 aes(y = ..density..)) + 
 ## [... everything else ...]
Related