1

I am needing to produce normally distributed density plots with different total areas (summing to 1). Using the following function, I can specify the lambda - which gives the relative area:

sdnorm <-  function(x, mean=0, sd=1, lambda=1){lambda*dnorm(x, mean=mean, sd=sd)}

I then want to plot up the function using different parameters. Using ggplot2, this code works:

require(ggplot2)
qplot(x, geom="blank") + stat_function(fun=sdnorm,args=list(mean=8,sd=2,lambda=0.7)) +
  stat_function(fun=sdnorm,args=list(mean=18,sd=4,lambda=0.30))

enter image description here

but I really want to do this in base R graphics, for which I think I need to use the "curve" function. However, I am struggling to get this to work.

2 Answers 2

2

If you take a look at the help file for ? curve, you'll see that the first argument can be a number of different things:

The name of a function, or a call or an expression written as a function of x which will evaluate to an object of the same length as x.

This means you can specify the first argument as either a function name or an expression, so you could just do:

curve(sdnorm)

to get a plot of the function with its default arguments. Otherwise, to recreate your ggplot2 representation you would want to do:

curve(sdnorm(x, mean=8,sd=2,lambda=0.7), from = 0, to = 30)
curve(sdnorm(x, mean=18,sd=4,lambda=0.30), add = TRUE)

The result:

curve

Sign up to request clarification or add additional context in comments.

1 Comment

Ah! I now see what I was doing wrong - I didn't specify the "from" and the "to" arguments for the curve function. The default display is from 0 to 1. Well done - thanks.
1

You can do the following in base R

x <- seq(0, 50, 1)
plot(x, sdnorm(x, mean = 8, sd = 2, lambda = 0.7), type = 'l', ylab = 'y')
lines(x, sdnorm(x, mean = 18, sd = 4, lambda = 0.30))

EDIT I added ylab = 'y' and updated the picture to have the y-axis re-labeled.

enter image description here

This should get you started.

1 Comment

Well done - thanks! I hadn't thought of first defining x as a sequence and then obtaining values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.