簡體   English   中英

通過ggplot2的stat_smooth調整擬合線增量?

[英]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_bydplyr::dodplyr::do而不是分割數據。 如果你對此感興趣,我建議你閱讀更多有關dplyr內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM