ggplot可以同时显示x和y上y的回归吗?

时间:2013-02-20 04:41:57

标签: r ggplot2 linear-regression

我有一个双变量数据集:

set.seed(45)
require(mvtnorm)
sigma <- matrix(c(3,2,2,3), ncol=2) 
df <- as.data.frame(rmvnorm(100, sigma=sigma))
names(df) <- c("u", "v")

使用v设置ggplot作为因变量我可以轻松显示vu的“常规”最小二乘回归:

require(ggplot2)
qplot(u, v, data=df) + geom_smooth(aes(u, v), method="lm", se=FALSE)

...但我还希望在u(同时)显示v的最小二乘回归。

通过将不同的aes传递给geom_smooth,这是我天真地尝试这样做的方式:

last_plot() + geom_smooth(aes(v, u), method="lm", color="red", se=FALSE)

当然,这不太有用。第二个geom_smooth显示正确行的(我认为)。我期待它比第一条线有更陡的斜率。

此外,置信区间错误地形成。我并不特别关心这些,但我认为它们可能是一个线索。

我是否要求使用ggplot2无法轻松完成的事情?

编辑:这里有一点,显示我期望的行:

# (1) Least-squares regression of v on u
mod <- lm(v ~ u, data=df)
v_intercept <- coef(mod)[1]
v_slope <- coef(mod)[2]
last_plot() + geom_abline(
    intercept = v_intercept, 
    slope = v_slope, 
    color = "blue", 
    linetype = 2
)

# (2) Least-squares regression of u on v
mod2 <- lm(u ~ v, data=df)
u_intercept <- coef(mod2)[1]
u_slope <- coef(mod2)[2]
# NOTE: we have to solve for the v-intercept and invert the slope
# because we're still in the original (u, v) coordinate frame
last_plot() + geom_abline(
    intercept = - u_intercept / u_slope, 
    slope = 1 / u_slope, 
    color = "red", 
    linetype = 2
)

enter image description here

1 个答案:

答案 0 :(得分:0)

ggplot(df) + 
  geom_smooth(aes(u,v), method='lm') + 
  geom_smooth(aes(v,u), method='lm', colour="red")