Search code examples
rggplot2overlaydensity-plot

How should be a ggplot equivalent of plot + lines in R?


With plot and lines I can make multiple plots overlapped in the same range in R. For example, I can plot the density of a data and then simulate a density distribution in the same plot as follows:

plot(density(mtcars$mpg), col = "red")
polygon(density(mtcars$mpg), col = "red")
x <- seq(0, 50, length=1000)
hxn <- dnorm(x,mean=mean(mtcars$mpg), sd = sd(mtcars$mpg))
lines(x,hxn, col="green")

obtaining enter image description here

How can I do the same (introduce both the density of the data mtcars$mpg and the simulation (x,hxn) in the same plot) with ggplot? I would start by

library(ggplot2)
ggplot(mtcars,aes(x=mpg))+geom_density(color = "red", fill = "red")+xlim(0,40)

but then I do not know how to overlay the x,hxn data.

Thanks!


Solution

  • You can do this:

    ggplot(mtcars,aes(x=mpg))+
      geom_density(color = "red", fill = "red")+ 
      xlim(0,40) +
      stat_function(fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))
    

    enter image description here