如何在此图中添加回归线?我尝试了abline(),但它似乎仅适用于数据框,而我正在处理矩阵。
https://i.stack.imgur.com/fAeyL.png
这是我的图形代码:
plot(Extended[,1], Extended[,14], xlim=c(1877, 2017), ylim=c(-12, 15), pch=19, col = 'blue')
答案 0 :(得分:0)
使用ggplot通常更容易。
library(ggplot2)
Ex <- as.data.frame(Extended);
names(Ex) <- paste0('V', 1:ncol(Ex));
ggplot(Ex, aes(x = V1, y = V14)) +
geom_point(size = 4, col = 'blue') +
geom_smooth(method = 'lm') +
coord_cartesian(xlim = c(1877, 2017),
ylim = c(-12, 15))
对于基本方法,有无数种可视化效果的方法。 effects
软件包是执行此操作的一种非常通用的方法。这种工作方式是使用predictorEffect
函数并指定要绘制的效果。
library(effects)
data(mtcars)
model <- lm(mpg ~ hp, data = mtcars)
plot(predictorEffect('hp', model))
效果包具有一些非常通用的实现,可以完成很多事情。我建议阅读小插图以了解软件包的工作原理。
对于手动基准图版本,我们可以执行以下操作:
mtcars[, c('fit', 'lwr', 'upr')] <- predict(model, interval = 'predict')
mtcars <- mtcars[order(mtcars$hp),]
plot(y = mtcars$mpg, x = mtcars$hp,
pch=19, col = 'blue')
lines(y = mtcars$fit, x = mtcars$hp, col = 'green')
lines(y = mtcars$upr, x = mtcars$hp, col = 'red')
lines(y = mtcars$lwr, x = mtcars$hp, col = 'red')