I have a time series data for neighbourhood and crime rate per year (example below).
Neighbourhood year rate 1 2009 43.5 1 2010 34.7 1 2011 40.8 2 2009 28.9 2 2010 33.8 2 2011 24.4 . . . . . .
I applied spline regression by group (for each neighbourhood) by using plyr and ggplot. Both show plots for each Neighbourhood but does not show the model line (spline curve)
library(ggplot2) require(stats) # First try: # run spline regression by groupe: (for each Neighbourhood) models <- dlply(crime_df, "Neighbourhood", function(crime_df) lm(formula = crime_df$rate ~ bs(crime_df$year, 6 ))) #Extract coefficients ldply(models, coefficients) # get a plot for each neighbourhood d_ply(crime_df, "Neighbourhood", transform, plot(year, rate, main = unique(Neighbourhood), pch= 19)) lines(crime_df$year, fitted(models)) # to put spline curve on these plots but does not work: # Second try: # run spline regression by groupe: (for each Neighbourhood) by using tidy # I used geom_smooth to plot the model (spline curve) but did not work crime_df %>% ggplot(aes(x = year, y = rate, group = Neighbourhood)) + geom_point(color = palette_light()[]) + geom_smooth(method = lm, formula = crime_df$rate ~ splines::bs(crime_df$year, 6), se = FALSE) + labs(title = "spline") + theme_tq() + facet_wrap(~ Neighbourhood, scale = "free_y", ncol = 3) + scale_x_date(date_labels = "%Y")