1

我有一个双变量数据集:

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为因变量,我可以轻松地显示onggplot的“通常”最小二乘回归:vu

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

u...但我也想展示on的最小二乘回归v(同时)。

这就是我天真地尝试这样做的方式,方法是传递一个不同aes的 to 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
)

在此处输入图像描述

4

1 回答 1

0
ggplot(df) + 
  geom_smooth(aes(u,v), method='lm') + 
  geom_smooth(aes(v,u), method='lm', colour="red")
于 2013-02-20T04:45:40.743 回答