Search code examples
rggplot2smoothingloess

facet ggplot by span argument of loess smoother


I would like to make a single facetted plot (lattice style) by varying the span parameter to the loess smoother. I tried using a for loop as below but no plot was produced. If I were to use the ggsave function, the plots are saved separately.

In addition, I was wondering if there is a more parsimonious way to do such a task?

x <- rep(1:10,4)
y <- 1.2*x + rnorm(40,0,3)
s <- seq(0.2,0.8,0.1)

# plot the series of plots by varying the span parameter
for (s_i in s) {
    qplot(x, y, geom = 'c('point','smooth'), span = s_i)
}

Solution

  • Your approach will work just fine if you explicitly print the plot (and get rid of your extra ' mark):

    for (s_i in s) {
        print(qplot(x, y, geom = c('point','smooth'), span = s_i))
    }
    

    As for other ways to do it, I would recommend putting all your plots in a list

    changing_span = list()
    for (i in seq_along(s)) {
        changing_span[[i]] <- qplot(x, y, geom = c('point','smooth'), span = s[i]) +
            labs(title = paste("span:", s[i]))
    }
    

    Then you can plot all of them together with, e.g.,

    library(gridExtra)
    do.call(grid.arrange, changing_span)