Plot multiple normal curves in same plot

本小妞迷上赌 提交于 2019-12-12 01:56:02

问题


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


来源:https://stackoverflow.com/questions/27009641/plot-multiple-normal-curves-in-same-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!