4
votes

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.

2

2 Answers

6
votes

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")
3
votes

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