Piecewise regression with R: plotting the segments

后端 未结 3 1972
-上瘾入骨i
-上瘾入骨i 2020-12-23 14:48

I have 54 points. They represent offer and demand for products. I would like to show there is a break point in the offer.

First, I sort the x-axis (offer) and remove

3条回答
  •  长情又很酷
    2020-12-23 15:17

    Vincent has you on the right track. The only thing "weird" about the lines in your resulting plot is that lines draws a line between each successive point, which means that "jump" you see if it simply connecting the two ends of each line.

    If you don't want that connector, you have to split the lines call into two separate pieces.

    Also, I feel like you can simplify your regression a bit. Here's what I did:

    #After reading your data into dat
    Break <- 22.4
    dat$grp <- dat$offer < Break
    
    #Note the addition of the grp variable makes this a bit easier to read
    m <- lm(demand~offer*grp,data = dat)
    dat$pred <- predict(m)
    
    plot(dat$offer,dat$demand)
    dat <- dat[order(dat$offer),]
    with(subset(dat,offer < Break),lines(offer,pred))
    with(subset(dat,offer >= Break),lines(offer,pred))
    

    which produces this plot:

    enter image description here

提交回复
热议问题