Using user-defined functions within “curve” functi

2019-09-14 14:15发布

问题:

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

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.

回答1:

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:



回答2:

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.

This should get you started.