R语言:平滑曲线函数选型与曲线坐标提取问题咨询
平滑曲线选择与拟合值提取方案
一、平滑曲线的选择
1. 修复loess拟合问题
你之前尝试loess失败,大概率是默认的span参数不合适——这个参数控制平滑程度,值越小曲线越贴近数据,值越大越平滑。如果你的数据中spread_favorite取值间隔小、样本量分布不均,调大span就能生成正常的平滑曲线。
示例代码:
plot <- ggplot(table, aes(x=spread_favorite, y=pct, size=games)) + geom_point() + # 可根据数据在0.5-1之间调整span值 geom_smooth(method = "loess", span = 0.75, se = FALSE, color="#e63946") + scale_y_continuous(labels = function(x) paste0(x*100, "%")) + scale_x_continuous(breaks = scales::pretty_breaks(n = 13))
2. 替代方案:广义可加模型(GAM)
如果数据量较大,loess的效率会降低,这时推荐用mgcv包的GAM模型,它对非线性趋势的拟合更灵活,也更适合大样本场景。
示例代码:
library(mgcv) plot <- ggplot(table, aes(x=spread_favorite, y=pct, size=games)) + geom_point() + geom_smooth(method = "gam", formula = y ~ s(x), se = FALSE, color="#457b9d") + scale_y_continuous(labels = function(x) paste0(x*100, "%")) + scale_x_continuous(breaks = scales::pretty_breaks(n = 13))
3. 多项式拟合(若趋势接近线性)
如果你的上升趋势接近线性,也可以用多项式回归,比如3次多项式,拟合成本更低:
plot <- ggplot(table, aes(x=spread_favorite, y=pct, size=games)) + geom_point() + geom_smooth(method = "lm", formula = y ~ poly(x, 3), se = FALSE, color="#1d3557") + scale_y_continuous(labels = function(x) paste0(x*100, "%")) + scale_x_continuous(breaks = scales::pretty_breaks(n = 13))
二、提取拟合的pct值
不管用哪种模型,都可以通过predict()函数生成对应spread_favorite的拟合值,步骤如下:
1. 以loess为例
# 先拟合loess模型 loess_fit <- loess(pct ~ spread_favorite, data = table, span = 0.75) # 生成原表所有spread_favorite对应的拟合值 table <- table %>% mutate(fitted_pct = predict(loess_fit, newdata = table))
此时table中的fitted_pct列就是你要的拟合值,比如-5.0对应的拟合值会替换原有的0.308。
2. 以GAM为例
gam_fit <- gam(pct ~ s(spread_favorite), data = table) table <- table %>% mutate(fitted_pct = predict(gam_fit, newdata = table))
内容的提问来源于stack exchange,提问作者Abartel
相关产品推荐
相关产品推荐

