[英]Adjusting fitted line increment by stat_smooth of ggplot2?
我正在使用ggplot2的stat_smooth的黃土方法來擬合我的數據。 我原始數據的X增量為1年。 然而,stat_smooth黃土的擬合線給我X'增量為0.522。 我想知道有沒有辦法調整stat_smooth返回的擬合線的增量? 基本上,將X增量保持為原始長度。 非常感謝!
print(ggplot(orig_data, aes(Year,Value, col=County)) + geom_point(na.rm = T) +
stat_smooth(alpha=.2,size=1,se=F,method="loess",formula = y~x, span = 0.5,
aes(outfit=fit<<-..y..,outx=fit_x<<-..x..)) + theme(legend.position="none"))
為了使loess
平滑地適應不同的數據段,我們需要分割數據。 使用內置的mtcars
作為一個例子,擬合一個黃土線,以wt
為單位平滑mpg
,每個cyl
值單獨平滑,我們可以這樣做:
# split the data
data_list = split(mtcars, f = mtcars$cyl)
# fit loess to each piece
mods = lapply(X = data_list, FUN = function(dat) loess(mpg ~ wt, data = dat))
# predict on each piece (the default predictions will be only
# at the data points)
predictions = lapply(mods, predict)
# combine things back together
library(dplyr)
result = bind_rows(data_list)
result$pred = unlist(predictions)
在一個情節中展示結果:
ggplot(result, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point() +
geom_point(aes(y = pred), shape = 1) +
geom_line(aes(y = pred))
我只使用dplyr
作為好的bind_rows
函數,但是整個過程可以用dplyr::group_by
和dplyr::do
來dplyr::do
而不是分割數據。 如果你對此感興趣,我建議你閱讀更多有關dplyr
內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.