简体   繁体   English

通过ggplot2的stat_smooth调整拟合线增量?

[英]Adjusting fitted line increment by stat_smooth of ggplot2?

I am using the loess method of stat_smooth of ggplot2 to fit my data. 我正在使用ggplot2的stat_smooth的黄土方法来拟合我的数据。 The X increment of my original data is 1 year. 我原始数据的X增量为1年。 However, the fitted line by loess of stat_smooth gives me X' increment of 0.522. 然而,stat_smooth黄土的拟合线给我X'增量为0.522。 I am wondering is there a way to adjust the increments of the fitted line returned from stat_smooth? 我想知道有没有办法调整stat_smooth返回的拟合线的增量? Basically, to keep the X increment as its original length. 基本上,将X增量保持为原始长度。 Thanks so much! 非常感谢!

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"))

enter image description here 在此输入图像描述

To fit a loess smooth to different segments of data, we need to split up the data. 为了使loess平滑地适应不同的数据段,我们需要分割数据。 Using the built-in mtcars as an example, fitting a loess line smoothing mpg in terms of wt with a separate smooth for each cyl value, we can do this: 使用内置的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)

Demonstrating the results in a plot: 在一个情节中展示结果:

ggplot(result, aes(x = wt, y = mpg, color = factor(cyl))) +
    geom_point() +
    geom_point(aes(y = pred), shape = 1) +
    geom_line(aes(y = pred))

在此输入图像描述

I used dplyr only for the nice bind_rows function, but this whole process could be done with a dplyr::group_by and dplyr::do instead of splitting the data. 我只使用dplyr作为好的bind_rows函数,但是整个过程可以用dplyr::group_bydplyr::dodplyr::do而不是分割数据。 I'd encourage you to read more about dplyr if you're interested in that. 如果你对此感兴趣,我建议你阅读更多有关dplyr内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM