我正在为不同的因变量运行相同的多元模型集。我想基于控制z的模型生成不同y与x的预测值,然后将它们绘制在相同的ggplot2中,使得每个模型获得不同的颜色。下面的代码生成两个模型,用于控制z的x和y1和y2之间的关系,不确定性然后只绘制其中一个:
require(ggplot2)
set.seed(123)
dat <- data.frame(x = rnorm(100), z = rnorm(100), y1 = rnorm(100), y2 = rnorm(100))
dat1 <- dat[,c(1,2,3)]
dat2 <- dat[,c(1,2,4)]
mod1 <- lm(y1 ~ x + z, data = dat1)
mod2 <- lm(y2 ~ x + z, data = dat2)
dat1$mod1 <- predict(mod1, newdata =dat1)
err <- predict(mod1, newdata =dat1, se = TRUE)
dat1$ucl <- err$fit + 1.96 * err$se.fit
dat1$lcl <- err$fit - 1.96 * err$se.fit
dat2$mod2 <- predict(mod2, newdata =dat2)
err <- predict(mod2, newdata =dat2, se = TRUE)
dat2$ucl <- err$fit + 1.96 * err$se.fit
dat2$lcl <- err$fit - 1.96 * err$se.fit
ggplot(dat1) +
geom_point(aes(x = x, y = mod1), size = .8, colour = "black") +
geom_smooth(data = dat1, aes(x= x, y = mod1, ymin = lcl, ymax = ucl), size = 1, colour = "darkblue", se = TRUE, stat = "smooth", method = "lm")
如果框架不同,有关如何添加第二个图的任何想法吗?
感谢您的帮助。
答案 0 :(得分:2)
只需使用data=dat2
和y=mod2
添加新图层。
我把点和线做成了红色。
ggplot(dat1) +
geom_point(aes(x = x, y = mod1), size = .8, colour = "black") +
geom_smooth(data = dat1, aes(x= x, y = mod1, ymin = lcl, ymax = ucl), size = 1, colour = "darkblue", se = TRUE, stat = "smooth", method = "lm") +
geom_point(data=dat2, aes(x = x, y = mod2), size = .8, colour = "red") +
geom_smooth(data = dat2, aes(x= x, y = mod2, ymin = lcl, ymax = ucl), size = 1,
colour = "red", se = TRUE, stat = "smooth", method = "lm")