I'm trying to fit a unique nth-degree polynomial fit to each facet in a facet-wrapped ggplot, but can't quite seem to get this to work.
One can use a uniform 1st degree linear fit for all facets with the following:
library(ggplot2)
df <- diamonds
polys <- c(2, 2, 2, 2, 2)
custom.smooth <- function(formula, data,...) {
smooth.call <- match.call()
smooth.call[[1]] <- lm
eval.parent(smooth.call)
}
ggplot(df, aes(x=carat, y=price)) +
geom_point(alpha=0.1) +
facet_wrap(~cut, scales='free') +
stat_smooth(method='custom.smooth')
What I can't figure out is how to use the ith integer in polys as the polynomial degree for the ith facet in the plot.
Does anyone know how to achieve this behavior? Any help others can offer would be greatly appreciated!
