2016-11-17 136 views
0

如何繪製使用ggplot的最佳擬合線的曲線?我最好的猜測是我需要改變stat_smooth參數,但我不知道如何。我的目標就像下圖中的黑線。 enter image description here使用ggplot繪製曲線擬合

vv<-structure(list(X = 16:19, school = structure(c(3L, 3L, 3L, 3L), .Label = c("UCB", "UCD", "UIUC"), class = "factor"), year = 2009:2012, mean = c(15.60965, 16.785, 16.77725, 15.91729), sd = c(6.483547,6.852999, 6.327013, 6.74991)), .Names = c("X", "school", "year", "mean", "sd"), row.names = 16:19, class = "data.frame") 

ggplot(vv, aes(x = year, y = mean)) + 
    ggtitle("scores")+ 
    geom_point() + 
    stat_smooth(method = "lm", col = "red") 
+0

也許'geom_smooth(method =「lm」,col =「red」,formula = y〜poly(x,2))',但難以做更有趣的四點 – user20650

回答

0

你可以嘗試改變配方:

ggplot(vv, aes(x = year, y = mean)) + 
    ggtitle("scores")+ 
    geom_point() + 
    stat_smooth(method = "lm", formula = y ~ splines::bs(x, 3), col = "red") 

enter image description here

+0

你能解釋一下這個公式嗎? 'splines'的東西? Im new to ggplot – Rilcon42

+1

默認行基於公式'y〜x'。 @HubertL使用更靈活的樣條函數。如果你先加載'splines'包(通過運行'library(splines)',你不需要在'stat_smooth'裏面聲明包名,'y〜bs(x,3)'是一個迴歸公式。使用B樣條基函數對'y'進行建模如果您對樣條函數還不熟悉,則更簡單的方法是使用二階多項式函數:stat_smooth(method =「lm」,formula = y〜poly(x ,2),col =「red」)'你也可以輸入'x + I(x^2)'而不是'poly(x,2)'。 – eipi10

0

或者乾脆這個(黃土),儘管你會得到由於空間太小的非常小的數據一些警告,但它的作品:

ggplot(vv, aes(x = year, y = mean)) + 
    ggtitle("scores") + 
    geom_point(size=3) + 
    stat_smooth(col = "red") 

enter image description here