Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a simple piecewise linear function?

Tags:

r

enter image description here The image illustrates my plotting objective. On this image, ignore the vertical slope on x1. total non-sense. The function is simply not defined after x takes on value x1 or greater OR y results in 0.

I'm having the following piecewise linear function with two conditions. How do you plot that in R? Semantically I want to make the statement: "if x equals or is greater than 20(x1), y must be zero, otherwise y equals mx+y1−mx1." . This slope muss decrease and set y to zero at 20.

f ( x ) = { m x + y 1 − m x 1 if  0 ≤ x < x 1 0 if  x ≥ x 1

So far, i tried this (uncertain how to set y1)

m <- -2
x1 <- 20
y1 <- ???
x <- seq(0, 100, 1)
fx <- (0 <= x & x < x1) * (m*x + y1 - m*x) + (x >= x1) * 0
plot(x, fx)

Of course, this results in an error.

Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' and 'y' lengths differ

I'm uncertain how to represent the y and y1.

like image 866
feder Avatar asked Sep 11 '13 09:09

feder


2 Answers

Define the function you need:

myf<-function(x, x1=20, y1=50, m=-2){ 
  firstInds<-intersect(which(x >= 0), which(x < x1)) 
  y<-x
  y[firstInds]<-m*x[firstInds]+y1-m*x1
  y[-firstInds]<-0
  y
}

And then use it:

x<-1:50
plot(x, myf(x))

Simple as that.

Just the illustration

If you want lines connecting the dots you can do

plot(x, myf(x), ylab="Y", xlab="X"); lines(x, myf(x), col="red")
like image 155
Dr. Mike Avatar answered Sep 25 '22 01:09

Dr. Mike


For this kind of plot, the simplest is probably to use function curve:

m <- -2
x1 <- 20
y1 <- 40

plot(NA,xlim=c(0,40),ylim=c(0,100), xaxs="i",yaxs="i") #Setting first an empty plot 
                                                       #where to plot your curve
curve(m*x+y1-m*x1, from=0, to=x1, add=TRUE)            #Then your curve
like image 44
plannapus Avatar answered Sep 27 '22 01:09

plannapus