如何绘制 R 中 lmer 回归模型的估计值?
How to plot estimate values for a lmer regression model in R?
我有这样的数据:
height <- c(1,2,3,4,2,4,6,8)
weight <- c(12,13,14,15,22,23,24,25)
type <- c("Wheat","Wheat","Wheat","Wheat","Rice","Rice","Rice","Rice")
set <- c(1,1,1,1,2,2,2,2)
dat <- data.frame(set,type,height,weight)
我 运行 一个 lmer 模型,在 R 中设置为随机效应:
mod <- lmer(weight~height + type + (1|set), data = dat)
现在,我想绘制模型的估计值并绘制回归图,x 轴为权重,y 轴为高度,facet(~type)
我使用预测函数如下
dat$pred <- predict(mod, type = "response")
我想实现一个如下所示的 ggplot:
ggplot(dat,aes(x = weight, y = height)) +
geom_point() + geom_smooth(method="lm", fill=NA) + facet_grid(~ type, scales = "free")
但是,我注意到预测函数只有一个输出。我如何绘制它以实现与上述相同的效果?或者我是否必须存储两个不同的预测响应,然后将其插入到 ggplot 的 x,y 中?
我可以调整您的绘图以显示原始值与预测值,如下所示:
ggplot(dat,aes(y = height)) +
geom_point(aes(x = weight)) +
geom_line(aes(x = pred)) +
facet_grid(~ type, scales = "free")
在您的示例图中,尽管模型中的结果变量 weight
在 x 轴上,但令人困惑。通常你会在 y 轴上有 outcome/predicted 变量,所以我会绘制你的模型预测:
ggplot(dat,aes(x = height)) +
geom_point(aes(y = weight)) +
geom_line(aes(y = pred)) +
facet_grid(~ type, scales = "free")
我有这样的数据:
height <- c(1,2,3,4,2,4,6,8)
weight <- c(12,13,14,15,22,23,24,25)
type <- c("Wheat","Wheat","Wheat","Wheat","Rice","Rice","Rice","Rice")
set <- c(1,1,1,1,2,2,2,2)
dat <- data.frame(set,type,height,weight)
我 运行 一个 lmer 模型,在 R 中设置为随机效应:
mod <- lmer(weight~height + type + (1|set), data = dat)
现在,我想绘制模型的估计值并绘制回归图,x 轴为权重,y 轴为高度,facet(~type)
我使用预测函数如下
dat$pred <- predict(mod, type = "response")
我想实现一个如下所示的 ggplot:
ggplot(dat,aes(x = weight, y = height)) +
geom_point() + geom_smooth(method="lm", fill=NA) + facet_grid(~ type, scales = "free")
但是,我注意到预测函数只有一个输出。我如何绘制它以实现与上述相同的效果?或者我是否必须存储两个不同的预测响应,然后将其插入到 ggplot 的 x,y 中?
我可以调整您的绘图以显示原始值与预测值,如下所示:
ggplot(dat,aes(y = height)) +
geom_point(aes(x = weight)) +
geom_line(aes(x = pred)) +
facet_grid(~ type, scales = "free")
在您的示例图中,尽管模型中的结果变量 weight
在 x 轴上,但令人困惑。通常你会在 y 轴上有 outcome/predicted 变量,所以我会绘制你的模型预测:
ggplot(dat,aes(x = height)) +
geom_point(aes(y = weight)) +
geom_line(aes(y = pred)) +
facet_grid(~ type, scales = "free")