2017-09-04 185 views
0

我有一個二次迴歸模型。我想將該模型的 擬合迴歸線添加到散點圖。我的首選是使用ggplot2。 我可以繪製散點圖,但是當我使用「stat_smooth()」 指定公式時,出現以下警告,並且擬合的 線未繪製在散點圖上。使用ggplot在散點圖上繪製迴歸線

警告消息: 1: 'newdata' 有80行,但發現變量有24行 2:計算在stat_smooth()失敗: 參數意味着,不同的行數:80,24

我的代碼如下。有人可以請指導我,我應該怎麼做 不同,以便我可以使用ggplot在散點圖 圖中擬合迴歸線。

代碼:

library(gamair) 
library(ggplot2) 
data(hubble) 

names(hubble)[names(hubble) == "y"] <- c("velocity") 
names(hubble)[names(hubble) == "x"] <- c("distance") 

hubble$distance.sqr <- hubble$distance^2 
model2.formula <- hubble$velocity ~ hubble$distance + 
    hubble$distance.sqr - 1 
model2.hbl <- lm(model2.formula, data = hubble) 
summary(model2.hbl) 

model2.sp <- ggplot(hubble, aes(x = distance, y = velocity)) + 
    geom_point() + labs(title = "Scatter Plot between Distance & Velocity", 
    x = "Distance", y = "Velocity") 
model2.sp + stat_smooth(method = "lm", formula = hubble$velocity ~ 
    hubble$distance + hubble$distance.sqr - 1) 

回答

1

我覺得這裏的問題是你如何指定二次公式。對於平方項,您可以使用I(x^2)poly(x, 2)。例如:

ggplot(hubble, aes(x, y)) + 
    geom_point() + 
    stat_smooth(method = "lm", 
       formula = y ~ x + poly(x, 2) - 1) + 
    labs(x = "Distance", y = "Velocity") 

enter image description here

+0

非常感謝,這真的不錯! – Soly

+0

不客氣。如果解決了您的問題,請接受答案。 – neilfws

+0

當然,再次感謝! – Soly

0

這裏是基於 「英里」 數據集MWE:

library(ggplot2) 

ggplot(mpg, aes(x = hwy, y = displ)) + 
    geom_point(shape = 1) + 
    geom_smooth(method = lm, se = FALSE)