1
votes

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
Perhaps this link helps stackoverflow.com/questions/1376967/…akrun
It's 3 lines in base R plotting. I think this is an instance where it's just easier: plot(NA,xlim=c(-4,4),ylim=c(0,1));curve(dnorm(x,mean=1,sd=0.5), col="blue", add=TRUE);curve(dnorm(x,mean=0,sd=1), col="red", add=TRUE)thelatemail
This worked great - thanks!arrrrRgh

1 Answers

9
votes

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')
)