使用来自晶格包的xyplot()绘制线性回归的观测值和拟合值 [英] Plot the observed and fitted values from a linear regression using xyplot() from the lattice package
问题描述
我可以创建简单的图形.我想在同一张图上观察和预测值(通过线性回归).我打算说Yvariable
与Xvariable
.只有1个预测变量,只有1个响应.我怎样才能在同一张图中添加线性回归曲线?
I can create simple graphs. I would like to have observed and predicted values (from a linear regression) on the same graph. I am plotting say Yvariable
vs Xvariable
. There is only 1 predictor and only 1 response. How could I also add linear regression curve to the same graph?
因此,总结需要以下帮助:
So to conclude need help with:
- 分析实际情况并预测两者
- 绘制回归线
推荐答案
此处是将单个图中的观测值和预测值作为点的一种选择.在观察点上获得回归线比较容易,我在第二点说明了
Here is one option for the observed and predicted values in a single plot as points. It is easier to get the regression line on the observed points, which I illustrate second
首先是一些虚拟数据
set.seed(1)
x <- runif(50)
y <- 2.5 + (3 * x) + rnorm(50, mean = 2.5, sd = 2)
dat <- data.frame(x = x, y = y)
适合我们的模型
mod <- lm(y ~ x, data = dat)
将模型输出合并并观察到的x
放入绘图仪的单个对象
Combine the model output and observed x
into a single object for plott
res <- stack(data.frame(Observed = dat$y, Predicted = fitted(mod)))
res <- cbind(res, x = rep(dat$x, 2))
head(res)
加载晶格并绘制图
require("lattice")
xyplot(values ~ x, data = res, group = ind, auto.key = TRUE)
生成的图应与此类似
要在观察到的数据上仅获得回归线,并且回归模型是一个简单的直线模型(根据我展示的模型),那么您可以绕开其中的大部分并仅使用
To get just the regression line on the observed data, and the regression model is a simple straight line model as per the one I show then you can circumvent most of this and just plot using
xyplot(y ~ x, data = dat, type = c("p","r"), col.line = "red")
(也就是说,您甚至不需要拟合模型或为绘图绘制新数据)
(i.e. you don't even need to fit the model or make new data for plotting)
生成的图应该像这样
第一个示例的替代方法(可以与将为回归线提供系数的任何事物一起使用)是编写自己的面板函数-并不像看起来那样令人恐惧
An alternative to the first example which can be used with anything that will give coefficients for the regression line is to write your own panel functions - not as scary as it seems
xyplot(y ~ x, data = dat, col.line = "red",
panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
panel.abline(coef = coef(mod), ...) ## using mod from earlier
}
)
这是上面图2中的图,但是是手工绘制的.
That gives a plot from Figure 2 above, but by hand.
假设您已使用插入符号完成了此操作,然后
Assuming you've done this with caret then
mod <- train(y ~ x, data = dat, method = "lm",
trControl = trainControl(method = "cv"))
xyplot(y ~ x, data = dat, col.line = "red",
panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
panel.abline(coef = coef(mod$finalModel), ...) ## using mod from caret
}
)
将产生与上面的图2相同的图.
Will produce a plot the same as Figure 2 above.
这篇关于使用来自晶格包的xyplot()绘制线性回归的观测值和拟合值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!