How can I overlay 2 normal distribution curves on the same plot?

14,963

Solution 1

use the functions lines or points, i.e.

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

also, check the function par (using ?par ) for plotting options, common options include labels (xlab/ylab), plotlimits (xlim/ylim), colors(col), etc...

Solution 2

You have a couple of options

Using base R

  • You can use the plot.function method (which calls curve to plot a function). This is what is called if you call plot(functionname)

You will probably need to roll your own function so this will work. Also, you will need to set up the ylim so the whole range of both functions is shown.

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

Using ggplot2

ggplot has a function stat_function that will impose a function on a plot. The examples in ?stat_function show how to add two Normal pdf functions with different means to the same plot.

Share:
14,963
StatsViaCsh
Author by

StatsViaCsh

Updated on June 05, 2022

Comments

  • StatsViaCsh
    StatsViaCsh almost 2 years

    I'm brand new to R, and I'm facing a problem without much in- class resources. I need to do something that I'm sure is very simple. Can someone point me in the right direction? This is my task:

    Let X denote the monthly return on Microsoft Stock and let Y denote the monthly return on Starbucks stock. Assume that X∼N(0.05,(0.10)2) and Y∼N(0.025,(0.05)2).

    Using a grid of values between –0.25 and 0.35, plot the normal curves for X and Y. Make sure that both normal curves are on the same plot.

    I've only been able to get a randomly generated normal distribution generated, but not both on the same plot, and not by specifying mean and st dev. Big thanks in advance.