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 no problem plotting that function by manually specifying values for each parameter.
c = 4
w = 6
pl = 0
pr = 1
Ultimately, i will want to plot thousands of curves, so I want to be able to tell R that the parameter estimates are in a table. Each row is the 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 of these curves on the same graph at once? Thanks in advance!!
I would just loop over your rows. You can do this
hzf <- function(x, pl,pr,w,c) 1-(pl+(0.5*(pr-pl))*(1+tanh(2*(x-c)/w)))
for(i in 1:nrow(hzdata)) {
with(hzdata[i,],
curve(hzf(x,pl,pr,w,c), xlim=c(-27,50), ylim=c(0,1),
lwd=3,col=i, add=i!=1)
)
}
which gives
Here is one way to create a generic function that can be used with a formula and a data.frame of variables (column names need to match arguments used in formla) using quote
and eval
## 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With