如何通过 ggplot2 中的连续交互来连续绘制?

机器算法验证 r 回归 ggplot2 相互作用
2022-03-22 19:50:21

假设我有数据:

x1 <- rnorm(100,2,10)
x2 <- rnorm(100,2,10)
y <- x1+x2+x1*x2+rnorm(100,1,2)
dat <- data.frame(y=y,x1=x1,x2=x2)
res <- lm(y~x1*x2,data=dat)
summary(res)

我想通过连续交互绘制连续图,使得 x1 在 X 轴上,x2 由 3 条线表示,一条代表 x2,Z 得分为 0,一条代表 Z 得分为 +1,另一条代表 a Z 分数为 -1,每条线都有单独的颜色并带有标签。我怎样才能使用ggplot2做到这一点?

例如,它可能看起来像这样(当然有不同颜色的线条而不是不同的线条类型): 示例图像

2个回答

这是我的模拟数据集版本:

x1 <- rnorm(100,2,10)
x2 <- rnorm(100,2,10)
y <- x1+x2+x1*x2+rnorm(100,1,2)
dat <- data.frame(y=y,x1=x1,x2=x2)
res <- lm(y~x1*x2,data=dat)
z1 <- z2 <- seq(-1,1)
newdf <- expand.grid(x1=z1,x2=z2)

library(ggplot2)
p <- ggplot(data=transform(newdf, yp=predict(res, newdf)), 
            aes(y=yp, x=x1, color=factor(x2))) + stat_smooth(method=lm)
p + scale_colour_discrete(name="x2") + 
  labs(x="x1", y="mean of resp") + 
  scale_x_continuous(breaks=seq(-1,1)) + theme_bw()

我让您管理有关 x/y 轴标签和图例定位的详细信息。

在此处输入图像描述

使用 Z 分数为 0( y0列)、-1(y1m列)和 1(y1p列)计算 y 的估计值

dat$y0 <- res$coefficients[[1]] + res$coefficients[[2]]*dat$x1 + res$coefficients[[3]]*0 + res$coefficients[[4]]*dat$x1*0
	dat$y1m <- res$coefficients[[1]] + res$coefficients[[2]]*dat$x1 + res$coefficients[[3]]*-1 + res$coefficients[[4]]*dat$x1*-1
dat$y1p <- res$coefficients[[1]] + res$coefficients[[2]]*dat$x1 + res$coefficients[[3]]*1 + res$coefficients[[4]]*dat$x1*1

用 base 绘制线条plot()

plot(dat$x1, dat$y0, type="l", xlab="x1", ylab="Estimates")
lines(dat$x1, dat$y1m, col="red")
lines(dat$x1, dat$y1p, col="blue")

在此处输入图像描述

要使用 ggplot,您可以调用geom_line

ggplot(dat, aes(x1, y0)) + geom_line() +
    geom_line(aes(x1, y1m), color="red") +
    geom_line(aes(x1, y1p), color="blue") +
    theme_bw() + opts(title="") + xlab("x1") + ylab("Estimates")

在此处输入图像描述