简体   繁体   中英

Adjusting fitted line increment by stat_smooth of ggplot2?

I am using the loess method of stat_smooth of ggplot2 to fit my data. The X increment of my original data is 1 year. However, the fitted line by loess of stat_smooth gives me X' increment of 0.522. I am wondering is there a way to adjust the increments of the fitted line returned from stat_smooth? Basically, to keep the X increment as its original length. 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. 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:

# 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. I'd encourage you to read more about dplyr if you're interested in that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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