Plot multiple normal curves in same plot

2019-09-17 02:49发布

问题:

I'm interested in creating an example plot (ideally using ggplot) that will display two normal curves with different means and different standard deviations. I've discovered ggplot's stat_function() argument but am not sure how to get a second curve on the same plot.

This code produces one curve:

ggplot(data.frame(x = c(-4, 4)), aes(x)) + stat_function(fun = dnorm)

Any advice on ways to get a second curve? Or maybe simpler to do in base package plotting?

回答1:

Just in case you also want to do it in ggplot (it's also 3 lines...).

ggplot(data.frame(x = c(-4, 4)), aes(x)) + 
  stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col='red') +
  stat_function(fun = dnorm, args = list(mean = 1, sd = .5), col='blue')

In case you have more than two curves, it may be better to use mapply for this. That makes it slightly more difficult. But for many functions it is probably worth it.

ggplot(data.frame(x = c(-4, 4)), aes(x)) + 
  mapply(function(mean, sd, col) {
    stat_function(fun = dnorm, args = list(mean = mean, sd = sd), col = col)
  }, 
  # enter means, standard deviations and colors here
  mean = c(0, 1, .5), 
  sd = c(1, .5, 2), 
  col = c('red', 'blue', 'green')
)