Add a regression line segment to the graph

I have 4 regression lines and I want to have them in one plot. Here's my simple code:

data = read.csv("TEST.csv", header = FALSE)
plot(data$V1,data$V2)
fit <- lm(data$V2~data$V1)
abline(fit, col=1)

data1 = read.csv("TEST1.csv", header = FALSE)
fit1 <- lm(data1$V2~data1$V1)
abline(fit1, col=2)

data2 = read.csv("TEST2.csv", header = FALSE)
fit2 <- lm(data2$V2~data2$V1)
abline(fit2, col=3)

data3 = read.csv("TEST3.csv", header = FALSE)
fit3 <- lm(data3$V2~data3$V1)
abline(fit3, col=4)

      

and here is the plot: Regression plot

but that's not what I want to have. The black line is fine, but for the red, blue and green lines, I just want to have a segment of those lines close to the data points. For example, only the green line segment is between 3 and 4. The datasets are located here:

TEST.csv: https://www.dropbox.com/s/aphd5ts9hxlm2wj/TEST.csv?dl=0

TEST1.csv: https://www.dropbox.com/s/dp3diwu4tuynbjp/TEST1.csv?dl=0

TEST2.csv: https://www.dropbox.com/s/b6zr88ottf3wmjg/TEST2.csv?dl=0

TEST3.csv: https://www.dropbox.com/s/o0qc2987gb04g7m/TEST3.csv?dl=0

+3


source to share


1 answer


One way to do this is to use clip

:

data = read.csv("TEST.csv", header = FALSE)
plot(data$V1,data$V2)
fit <- lm(data$V2~data$V1)
abline(fit, col=1)

data1 = read.csv("TEST1.csv", header = FALSE)
clip(min(data1$V1), max(data1$V1), min(data1$V2), max(data1$V2))
fit1 <- lm(data1$V2~data1$V1)
abline(fit1, col=2)

data2 = read.csv("TEST2.csv", header = FALSE)
clip(min(data2$V1), max(data2$V1), min(data2$V2), max(data2$V2))
fit2 <- lm(data2$V2~data2$V1)
abline(fit2, col=3)

data3 = read.csv("TEST3.csv", header = FALSE)
clip(min(data3$V1), max(data3$V1), min(data3$V2), max(data3$V2))
fit3 <- lm(data3$V2~data3$V1)
abline(fit3, col=4)

      



So what I am doing is limiting the set line plots to the appropriate data ranges. The limits are very tight, but you can scale them to get inline lines that expand slightly outside of the data range.

+3


source







All Articles