问题
I have a spectral plot with 2 straight lines, which I made with the following commands: (a is the slope from the left part of the spectrum, b the right. the boundary is 3200 Hz here)
a=0.009909
b=-0.003873
plot(spec, type="l", main...)
abline(a, col="orange")
abline(b, col="skyblue")
abline(v=3200, lty=2)

What I would like to do is to draw the orange line until 3200 Hz and the skyblue line from 3200 Hz like the following plot (roughly created by photoshop, sorry):

Is that with the function abline() possible? Or is there any way to do that?
Thank you very much!
回答1:
edited to fix an error
Here is a basic example that should be extendable to your data. It relies on generating the coefficients for the lines of best fit for each subset of data first using glm
and then calling these in a lines
statement.
test <- c(1.4, 2.3, 3.8, 3.6, 5.9, 5.4, 7.6, 7.4, 8.1, 8.7, 7.4, 6.9,
5.4, 4.7, 2.7, 1.8, 1.1)
plot(test,type="l",ylim=c(0,12))
fit1 <- glm(test[1:8] ~ I(1:8))
fit2 <- glm(test[9:17] ~ I(1:9))
# ...$coefficients[2] is the slope, ...$coefficients[1] is the intercept
lines(1:9, 1:9 * fit1$coefficients[2] + fit1$coefficients[1],col="red")
lines(9:17,1:9 * fit2$coefficients[2] + fit2$coefficients[1],col="blue")

回答2:
If you have the fitted models, then the best solution is to use the predict()
method to generate predictions for a set of equally spaced points over the intervals of interest.
Using the data from @thelatemail's answer
df <- data.frame(y = c(1.4, 2.3, 3.8, 3.6, 5.9, 5.4, 7.6, 7.4, 8.1,
8.7, 7.4, 6.9, 5.4, 4.7, 2.7, 1.8, 1.1),
x = 1:17,
ind = rep(c(TRUE,FALSE), times = c(8,9)))
fit1 <- lm(y ~ x, data = df, subset = ind)
fit2 <- lm(y ~ x, data = df, subset = !ind)
## regions in a new data frame over which to predict
r1 <- data.frame(x = seq(from = 1, to = 8, length.out = 20))
r2 <- data.frame(x = seq(from = 9, to = 17, length.out = 20))
## predict
p1 <- predict(fit1, newdata = r1)
p2 <- predict(fit2, newdata = r2)
## add lines to plot
plot(y ~ x, data = df, type = "l")
lines(p1 ~ x, data = r1, col = "red")
lines(p2 ~ x, data = r2, col = "blue")
This gives

This is a more flexible way of doing what you want than writing out the equation by hand, and works with many types of model where they have a predict()
method.
来源:https://stackoverflow.com/questions/13388963/how-to-draw-straight-lines-in-a-restrictive-area