How do I change colours of confidence interval lines when using `matlines` for prediction plot?

时间:2016-11-26 18:30:13

标签: r plot regression linear-regression lm

I'm plotting a logarithmic regression's line of best fit as well as the confidence intervals around that line. The code I'm using works well enough, except I'd rather that the confidence intervals both be "gray" (rather than the default "red" and "green"). Unfortunately, I'm not seeing a way to isolate them when specifying colour changes. I'd like

  • for the regression line: lty = 1, col = "black";
  • for confidence intervals to have: lty=2, col = "gray".

How can I achieve this? my code is of the sort:

R6cl <- lm(log(R6$y) ~ R6$x)
pR6cl <- predict(R6cl, interval="confidence")
plot(R6$x, log(R6$y), type = "p") 
matlines(x = R6$x, y = log(R6$y), lwd = 2, lty = 1, col = "black")

which produces:

enter image description here

2 个答案:

答案 0 :(得分:2)

colltylwd已经过矢量化。你可以使用

R6cl <- lm(log(y) ~ x, data = R6)  ## don't use $ in formula
pR6cl <- predict(R6cl, interval = "confidence")
plot(log(y) ~ x, data = R6)  ## Read `?plot.formula`
matlines(R6$x, pR6cl, lwd = 2, lty = c(1, 2, 2), col = c(1, 2, 2))

您可以查看Piecewise regression with a quadratic polynomial and a straight line joining smoothly at a break point中的最后一个数字,了解此代码的效果。

如果您不清楚为何我建议不要在模型公式中使用$,请阅读Predict() - Maybe I'm not understanding it

其他读者的旁注通知

OP有一个数据集,其中x已排序。如果您的x未排序,请务必先对其进行排序。有关详情,请参阅Messy plot when plotting predictions of a polynomial regression using lm() in R

答案 1 :(得分:1)

怎么样:

a = 1:10
b = c(2,1,2,4,5,5,3,7,4,10)

R6cl <- lm(log(b)~a)
pR6cl <- predict(R6cl, interval = "confidence")
plot(a, log(b), type = "p") 
lines(a, pR6cl[,1], lty = 1, col = "black")
lines(a, pR6cl[,2], lty = 2, col = "gray")
lines(a, pR6cl[,3], lty = 2, col = "gray")

给出了:

plot