在同一图中绘制多条正常曲线 [英] Plot multiple normal curves in same plot

查看:115
本文介绍了在同一图中绘制多条正常曲线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣创建一个示例图(理想情况下使用ggplot),它将显示具有不同方法和不同标准偏差的两条正态曲线。我发现ggplot的stat_function()参数,但不知道如何在同一个图上获得第二条曲线。

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?

推荐答案

为防万一您也想在 ggplot (它也是3行...)。

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

如果您有两条以上的曲线,为此使用 mapply 。这使得它稍微困难一些。但对于许多功能来说,这可能是值得的。

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

这篇关于在同一图中绘制多条正常曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆