Is there a faster way than for loops to use facet_wrap_paginate in R?

Viewed 278

I'm trying to use facet_wrap_paginate() from the ggforce package to apply facet_wrap() to a large number of facets that would be unreadable if on a single page. However, using a for() loop (as described in the vignette) to create each page is incredibly slow for my dataset, so I was wondering how I would go about vectorizing this process? Part of the issue I suspect is that I have nested the for() loop into a function so that I can apply it to a number of scenarios, and I'm guessing that it is effectively rebuilding the entire plot every time before selecting the correct page to display. If my assumption is correct, is there a way to instead of rebuilding the plot each time, just select the page from the plot that has been stored in memory?

library(tidyverse)
library(ggforce)

df <- mtcars

hist_plts <- function(data, var, title_vars, pages, x_low_lim = 0, x_up_lim = 50) {
    for (i in 1:pages) {
        plot <- data %>%
            filter({{ var }} >= x_low_lim, {{ var }} < x_up_lim) %>%
            ggplot(
                aes(
                    x = {{ var }} 
                )
            ) +
            geom_histogram(binwidth = 1) +
            labs(
                title = paste0("Count of mpg by ", title_vars),
                x = "MPG",
                y = " Count",
                caption = paste0("Page ", i, " of ", pages)
            ) +
            scale_x_continuous() +
            facet_wrap_paginate(
                ~cyl,
                scales = "free",
                nrow = 1,
                ncol = 1,
                page = i)
        
        print(plot)
    }
}

hist_plts(
    data = df,
    var = mpg,
    title_vars = "Cylinders",
    pages = 3)

0 Answers
Related