Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphing a function in R: how do I draw many curves using parameter values in a data table?

Tags:

function

plot

r

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

like image 224
Sean Stankowski Avatar asked Sep 08 '25 19:09

Sean Stankowski


2 Answers

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

enter image description here

like image 90
MrFlick Avatar answered Sep 10 '25 07:09

MrFlick


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)

enter image description here

like image 23
Rorschach Avatar answered Sep 10 '25 08:09

Rorschach