我需要擬合兩條簡單的線性回歸線,一條帶有“y = 父親”和“x = 兒子”,另一條帶有“y = 兒子”和“x = 父親”。我能夠毫無問題地做到這一點,并收集了正確的方程式。但是,我還需要將它們繪制在同一個散點圖上,這是我遇到麻煩的地方。我很好奇是否有一種方法可以將“y = 父親”和“x = 兒子”回歸線繪制到 y = 兒子和 x = 父親的散點圖上。或者有沒有辦法可以結合以下兩個情節?
ggplot(galton_heights, aes(x = father, y = son))
geom_point()
geom_abline(slope = 0.46139, intercept = 37.28761, col = "blue")
theme_bw()
ggplot(galton_heights, aes(x = son, y = father))
geom_point()
geom_abline(slope = 0.40713, intercept = 40.93831, col = "red")
coord_flip()
theme_bw()
有人告訴我,我的情節應該類似于上面的兩個單獨的圖表組合在一起。

uj5u.com熱心網友回復:
我想我的資料可能和你不一樣,但是原理是一樣的。讓我們對兒子的身高和父親的身高進行線性回歸,然后反之亦然
father_x <- lm(son ~ father, data = galton_heights)
son_x <- lm(father ~ son, data = galton_heights)
coef(father_x)
#> (Intercept) father
#> 33.886604 0.514093
coef(son_x)
#> (Intercept) son
#> 34.10745 0.48890
現在,顯然系數是不同的。根據父親身高計算兒子身高的公式是:
son = 0.514093 * father 33.886604
但如果我們采用其他回歸,我們也可以重新排列它以根據父親的身高求解兒子的身高:
father = 0.48890 * son 34.10745
son = (father - 34.10745)/0.48890
son = 2.045408 * father - 69.76365
這為我們繪制了兩條線的系數:
ggplot(galton_heights, aes(x = father, y = son))
geom_point()
geom_abline(aes(slope = 0.514093, intercept = 33.886604,
colour = "son height regressed\non father height"),
size = 2)
geom_abline(aes(slope = 2.045408, intercept = -69.76365,
color = "father height regressed\non son height"),
size = 2)
theme_bw()

注意翻轉坐標時的對稱性:
ggplot(galton_heights, aes(x = father, y = son))
geom_point()
geom_abline(aes(slope = 0.514093, intercept = 33.886604,
colour = "son height regressed\non father height"),
size = 2)
geom_abline(aes(slope = 2.045408, intercept = -69.76365,
color = "father height regressed\non son height"),
size = 2)
theme_bw()
coord_flip()

由reprex 包創建于 2022-02-12 (v2.0.1)
uj5u.com熱心網友回復:
對于第一部分,您可以簡單地使用geom_smooth來繪制線性回歸線:
ggplot(galton_heights, aes(x = father, y = son))
geom_point()
geom_smooth(method = "lm", se = FALSE)
theme_bw
對于問題的第二部分,這樣做并沒有什么意義,因為您應該更改軸。你可以這樣做:
ggplot(galton_heights, aes(x = father, y = son))
geom_point()
geom_smooth(method = "lm", se = FALSE, col = "blue")
geom_smooth(aes(y = father, x = son), method = "lm", se = FALSE, col = "red")
theme_bw()
但理論上是錯誤的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427678.html
上一篇:按日期順序繪制資料
下一篇:代表錯誤美學的箱線圖
