用R中的几个参数绘制一个函数 [英] Plot a function with several arguments in R

查看:275
本文介绍了用R中的几个参数绘制一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想绘制一个R函数:
$ b $ $ p $ weibull < - function(ALPHA,LAMBDA,T){
ALPHA * LAMBDA *(T ^(ALPHA-1))
}

所以函数需要参数alpha,lambda和T.我想要生成一个图,其中在一个图中alpha = 0.5,时间范围从0到2,lambda = 1,2,4,8,16,在另一个alpha = 1,时间范围从0到2,lambda = 1,2,4,8,16。



过去只用一个参数绘制函数,我已经使用曲线,然后完成ADD = TRUE,如果我想要在同一图上的另一条曲线。因此,例如,在过去我已经使用过:

  lambda < -  0.5 
pdf < - 函数(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 (生存,0,6,add = TRUE,col =plum4,lwd = 3)

但在这个例子中,函数只有一个参数,即x。而现在我想改变LAMBDA,T和ALPHA。曲线功能不起作用,我不知道如何解决这个问题。

解决方案

我会用plyr和ggplot2来做,

  weibull < - 函数(alpha,lambda,time){
data.frame(time = time,value = alpha * lambda *(time ^(alpha-1)))
}

library(plyr)
library(ggplot2)

params< - expand.grid(lambda = c(1,2,4,8,16) ,alpha = c(0.5,1))

all < - mdply(params,weibull,time = seq(0,2,length = 100))

ggplot (all,aes(time,value,color = factor(lambda)))+
facet_wrap(〜alpha,scales =free,ncol = 2)+ geom_line()


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.

解决方案

I'd do it with plyr and ggplot2,

weibull <- function(alpha, lambda, time){
  data.frame(time = time, value = alpha*lambda*(time^(alpha-1)))
}

library(plyr)
library(ggplot2)

params <- expand.grid(lambda = c(1, 2, 4, 8, 16), alpha = c(0.5, 1))

all <- mdply(params, weibull, time = seq(0, 2, length=100))

ggplot(all, aes(time, value, colour=factor(lambda)))+
  facet_wrap(~alpha,scales="free", ncol=2) + geom_line()

这篇关于用R中的几个参数绘制一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆