简体   繁体   中英

How to plot a simple piecewise linear function?

在此输入图像描述 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 ) = { mx + y 1 − mx 1 if 0 ≤ x < x 1 0 if x ≥ x 1

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

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

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.

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.

只是插图

If you want lines connecting the dots you can do

plot(x, myf(x), ylab="Y", xlab="X"); lines(x, myf(x), col="red")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM