2016-11-17 162 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