【问题标题】:How can I overlay 2 normal distribution curves on the same plot?如何在同一个图上叠加 2 条正态分布曲线?
【发布时间】:2013-05-14 00:06:38
【问题描述】:

我是 R 的新手,我正面临一个没有太多课堂资源的问题。我需要做一些我确信很简单的事情。有人可以指出我正确的方向吗?这是我的任务:

让 X 表示 Microsoft 股票的月回报率,让 Y 表示 星巴克股票的月收益。假设 X∼N(0.05,(0.10)2) Y∼N(0.025,(0.05)2)。

使用介于 –0.25 和 0.35 之间的值的网格,绘制正态曲线 对于 X 和 Y。确保两条正态曲线在同一个图上。

我只能生成随机生成的正态分布,但不能在同一个图上生成,也不能通过指定均值和标准差来生成。非常感谢。

【问题讨论】:

    标签: r statistics distribution


    【解决方案1】:

    使用函数线或点,即

    s <- seq(-.25,.35,0.01)
    plot(s, dnorm(s,mean1, sd1), type="l")
    lines(s, dnorm(s,mean2, sd2), col="red")
    

    另外,检查函数 par(使用 标准杆 ) 对于绘图选项,常用选项包括标签(xlab/ylab)、绘图限制(xlim/ylim)、颜色(col)等...

    【讨论】:

      【解决方案2】:

      你有几个选择

      使用基础 R

      • 您可以使用plot.function 方法(调用curve 来绘制函数)。如果你打电话给plot(functionname),这就是所谓的

      您可能需要推出自己的功能,这样才能奏效。此外,您还需要设置ylim,以便显示这两个功能的全部范围。

      # for example
      fooX <- function(x) dnorm(x, mean = 0.05, sd = 0.1)
      plot(fooX, from = -0.25, to = 0.35)
      # I will leave the definition of fooY as an exercise.
      fooY <- function(x) {# fill this is as you think fit!}
      # see what it looks like
      plot(fooY, from = -0.25, to = 0.35)
      # now set appropriate ylim (left as an exercise)
      # bonus marks if you work out a method that doesn't require this!
      myYLim <- c(0, appropriateValue)
      # now plot
      plot(fooX, from = -0.25, to = 0.35, ylim = myYLim)
      # add the second plot, (note add = TRUE)
      plot(fooY, from = -0.25, to = 0.35, add = TRUE)
      

      使用 ggplot2

      ggplot 有一个函数stat_function,它将在绘图上施加一个函数。 ?stat_function 中的示例显示了如何将两个具有不同均值的 Normal pdf 函数添加到同一个图中。

      【讨论】: