Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot multiple normal curves in same plot

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?

like image 526
arrrrRgh Avatar asked Jan 28 '26 16:01

arrrrRgh


1 Answers

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')
)
like image 59
shadow Avatar answered Jan 31 '26 08:01

shadow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!