Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

graphics - Plot a function with several arguments in R

Suppose I want to plot an R function:

weibull <- function(ALPHA, LAMBDA, T){
ALPHA*LAMBDA*(T^(ALPHA-1))
}

So the function takes the arguments alpha, lambda and T. I want to generate a plot where in one plot alpha =0.5, time ranges from 0 to 2 and lambda=1, 2, 4, 8, 16 and in another, alpha=1, time ranges from 0 to 2 and lambda=1, 2, 4, 8, 16.

In the past for plotting functions with just one argument, I've used curve and then done ADD=TRUE if I wanted another curve on the same plot. So for instance, in the past I've used:

lambda <- 0.5
pdf <- function(x){
lambda*exp(-lambda*x)
}
survival <- function(x){
exp(-lambda*x)
}
plot(curve(pdf, 0, 6), type="l", ylim=c(0, 1), lwd=3, ylab="", xlab="", xaxs="i", yaxs="i", main=expression(paste("Exponential Distribution ", lambda, "=0.5")), cex.main=2, cex.axis=2, cex.lab=2)
curve(survival, 0, 6, add=TRUE, col="plum4", lwd=3)

But in this example the functions just have one argument, which is x. Whereas, now I want to vary LAMBDA, T and ALPHA. The curve function does not work and I am not sure how else to approach this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you use curve, you can specify an expression with a free variable x that will get replaced by the range of values specified in your from=/to= parameters. For example you can do

weibull <- function(ALPHA, LAMBDA, T){
    ALPHA*LAMBDA*(T^(ALPHA-1))
}

lambda<-c(1, 2, 4, 8, 16)
col<-rainbow(length(lambda))
layout(matrix(1:2, nrow=1))
for(i in seq_along(lambda)) {
    curve(weibull(.5, lambda[i], x), from=0, to=2, add=i!=1, col=col[i], ylim=c(0,50), main="alpha=.5")
}
legend(1,50,lambda, col=col, lty=1)
for(i in seq_along(lambda)) {
    curve(weibull(1, lambda[i], x), from=0, to=2, add=i!=1, col=col[i], ylim=c(0,20), main="alpha=1")
}

which will produce a plot like

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...