Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"conditional" plots

Tags:

plot

r

I am curious how to plot function that is defined something like this:

 if(x < 1)
   f(x) = x/10 * 1.2
 if(x < 3)
   f(x) = x/12 * 1.7
 ...
 else
   f(x) = x/15 * 2

If the function was simple, say f(x) = x/10 * x/5 , then there would be no problem, and one could use curve() method. However I am not sure what is the best way to deal with more complex functions, like the one above. Any ideas? Bonus points, if ggplot() could be used :)

like image 268
mkk Avatar asked Dec 03 '22 07:12

mkk


2 Answers

Curve is still a possibility. (And as you read the statistical literature, this formulation shows up as I[x], "I" being for "indicator".)

curve( (x <1)*( (x/10)*1.2 ) +       # one line for each case
       (!(x <1)&(x<3) )*(x/12)*1.7 + # logical times (local) function
        (x >=3)*(x/15)*2 ,
        0,4)                         # limits

enter image description here

like image 178
IRTFM Avatar answered Dec 13 '22 19:12

IRTFM


Are you looking for something like stepfun?

fn <- stepfun(c(1,2,3,4,5),c(0,1,2,3,4,5))
plot(fn,verticals = FALSE)

enter image description here

The way you specify the function will be a bit different, but it's fairly easy to grasp once you've read ?stepfun and plotted some examples yourself.

like image 37
joran Avatar answered Dec 13 '22 18:12

joran