簡體   English   中英

將多個回歸線擬合到R中的散點圖

[英]fitting more than one regression line to a scatterplot in R

我試圖將回歸線擬合到這個關系angc~ext。 變量pch將數據分成兩組,每組我想要擬合一條回歸線

憑借其置信區間。 這是我的數據框(C):

"ext" "angc" "pch"
25 3.76288002820208 0
29 4.44255895177431 0
21 2.45214044383301 0
35 4.01334352881766 0
35 9.86225452423762 0
28 19.9304126868056 1
32 25.6984064030981 1
20 5.10582966112880 0
36 5.75603291081328 0
11 4.62311785943305 0
33 4.94401591414043 0
27 8.10039123328465 0
29 16.3882499757369 1
30 29.3492784626796 1
29 3.85960848290140 0
32 5.35857680326963 0
26 4.86451443776053 0
16 8.22008387344697 0
30 10.2212259432413 0
32 17.2519440101067 1
29 27.5011256290209 1

我的代碼:

c0 <-  C[C$pch == 0, ]
c1 <- C[C$pch == 1, ]
prd0 <- as.data.frame( predict( lm(c0$angc ~ c0$ext), interval = c("confidence") ) )
prd1 <- as.data.frame( predict( lm(c1$angc ~ c1$ext), interval = c("confidence") ) )
dev.new()
plot( C$angc ~ C$ext, type = 'n' )
points( c0$angc ~ c0$ext, pch = 17 ) # triangles
abline(lm(c0$angc ~ c0$ext)) # regression line
lines(prd0$lwr) # lower CI
lines(prd0$upr) # upper CI
points( c1$angc ~ c1$ext, pch = 1 ) # circles
abline(lm(c1$angc ~ c1$ext))
lines(prd1$lwr, type = 'l', lty = 3 )
lines(prd1$upr, type = 'l', lty = 3 )

我有兩個問題:

  1. 如何為圓圈獲得所需的回歸線? 它應該是一條幾乎垂直的線(檢查c1)
  2. 我沒有得到正確的置信區間

謝謝您的幫助,

桑蒂

ggplot2您可以相當有效地執行此操作:

ggplot(C, aes(x = ext, y = angc, shape = pch)) + geom_point() + 
     geom_smooth(method = "lm")

這將創建angc vs ext的散點圖( geom_point() ),其中點的形狀基於pch 此外,在圖中為pch每個唯一元素繪制回歸線。 名稱geom_smooth()來自這樣一個事實:它繪制了數據的平滑版本,在這種情況下是線性回歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM