Search code examples
rggplot2normal-distributionprobability-density

Understanding dnorm and geom_density


x <- seq(-4, 4, length.out = 100)
data.frame(x,  f = dnorm(x)) %>%
     ggplot(aes(x, f)) +
     geom_line()

imho, this should give the exact same plot as this:

x <- seq(-4, 4, length.out = 100)
data.frame(x,  f = dnorm(x)) %>%
   ggplot() +
   geom_density(aes(x))

How come it doesn't?


Solution

  • You are probably looking for stat_function

    x <- seq(-4, 4, length.out = 100)
    data.frame(x,  f = dnorm(x)) %>%
         ggplot(aes(x, f)) +
         geom_line() + 
         stat_function(fun=dnorm, geom="line", col=2, lty=2)