二変量データセットがあります:
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
簡単に示すことができます。v
u
require(ggplot2)
qplot(u, v, data=df) + geom_smooth(aes(u, v), method="lm", se=FALSE)
u
...しかし、 onの最小二乗回帰もv
(同時に)示したいと思います。
これは、私が素朴にそれをやろうとした方法aes
ですgeom_smooth
。
last_plot() + geom_smooth(aes(v, u), method="lm", color="red", se=FALSE)
もちろん、それはうまくいきません。2番目は適切な線の逆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
)