span argument not work working with loess fit in ggplot2?

3k views Asked by At

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

There are 2 answers

2
spotnag On BEST ANSWER

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.

2
bouncyball On

In my opinion, this probably has less to do with ggplot2 and more to do with your data. Observe:

plot.data.a <- plot.data[plot.data$group == 'a', ]
par(mfrow = c(2,2))
for(i in seq(.1, .9, length.out = 4)){
    plot(plot.data.a[,-1], main = paste('Span of', round(i, 2)))
    lines(loess(y ~ x, data = plot.data.a, span = i))
}

enter image description here

It seems as though varying the span has little to no visual impact of the loess fit.

So, as you were making your plots and varying the span, it seems likely that ggplot2 understood you were changing the span, it's just that the fits were relatively unchanged.