Search code examples
rggplot2loessfacet-grid

span argument not work working with loess fit in ggplot2?


I want need to change the span argument in the example plot,Example Plot

In the code I have written to get this plot I can't get the span to do anything other than the default of 0.2. I have a hunch it's got something to do with assigning the loess fit properly to each of the groups but what I've tried hasn't worked. I've made some example code to demonstrate the span argument not affecting the loess fit below.

xy <- rbind(data.frame(x=sort(rnorm(n=46, mean=5, sd=2)), y=1:46),data.frame(x=sort(rnorm(n=46, mean=7, sd=3)), y=1:46), data.frame(x=sort(rnorm(n=46, mean=4, sd=7)), y=1:46))


plot.data <- data.frame(group=letters[rep(1:3, each=46)], xy)

ggplot(plot.data, aes(x=x, y=y))+geom_smooth(method=loess, span=0.1, se=T,  col='black') + geom_point(alpha=0.7) + facet_wrap(~group)

Solution

  • Span is related to the geom_smooth(...) method call "loess", see this link for a helpful intro.

    Any data over 1000 data points defaults to method = "gam", as this is more efficient for large data sets.

    `geom_smooth()` using method = 'gam'
    

    Try explicitly stating method = loess, and then setting the span.

    geom_smooth(method = "loess", span = 0.3)
    

    Note: This exponentially increases the chart render time.