Plotting a function in R: how to draw many curves using parameter values ββin a data table?
I'm new to using R. I have a function with 4 parameters (c, w, pl, pr).
curve(1-(pl+(0.5*(pr-pl))*(1+tanh(2*(x-c)/w))),xlim=c(-27,50),ylim=c(0,1),lwd=3,col=2, add=T)
I am not trying to build this function manually by specifying values ββfor each parameter.
c = 4
w = 6
pl = 0
pr = 1
Ultimately I want to plot thousands of curves, so I want to tell R that the parameter estimates are in a table. Each row represents data for one curve
hzdata
pl pr w c
1 1 0 3 0
2 1 0 4 0
3 1 0 5 0
4 1 0 6 0
5 1 0 7 0
6 1 0 8 0
7 1 0 9 0
8 1 0 10 0
How do I tell R that I want to plot all these curves on the same graph at once? Thanks in advance!
+3
source to share
2 answers
Here is one way to create a generic function that can be used with formula and data.frame variables (column names must match the arguments used in formla) using quote
andeval
## Your formula, changed add=add and col=col to allow to vary
form <- quote(
curve(1-(pl+(0.5*(pr-pl))*(1+tanh(2*(x-c)/w))),xlim=c(-27,50),ylim=c(0,1),lwd=3,col=col,add=add)
)
plotFun <- function(params, form, colors) {
eval(form, as.list(c(params[1,], col=colors[1], add=F))) # plot the first
for (i in 2:nrow(params)) # plot the rest, adding to the first
eval(form, as.list(c(params[i,], col=colors[i], add=T)))
}
colors <- colorRampPalette(c("red", "yellow"))(nrow(hzdata))
plotFun(hzdata, form, colors=colors)
+1
source to share