Skip to content

Instantly share code, notes, and snippets.

@mccarthy-m-g
Created August 26, 2024 16:29
Show Gist options
  • Save mccarthy-m-g/a45aeb91cfad7e7a395a735ff53342bb to your computer and use it in GitHub Desktop.
Save mccarthy-m-g/a45aeb91cfad7e7a395a735ff53342bb to your computer and use it in GitHub Desktop.
Shiny module for paging through a faceted ggplot2 plot
# Create facet page slider module UI
facetPageUI <- function(id) {
tagList(
sliderInput(
NS(id, "facet_page"),
"Facet page:",
value = 1,
min = 1,
max = 2,
step = 1,
pre = "Page ",
ticks = FALSE
)
)
}
# Create module server for facet page slider
facetPageServer <- function(id, plot, facets, ncol = 4, nrow = 3) {
moduleServer(id, function(input, output, session) {
p_temp <- plot + facet_wrap_paginate(facets,
ncol = ncol, nrow = nrow,
page = input$facet_page)
# Only use pagination when the number of facets exceeds 12; this keeps
# the UI clean.
if (n_pages(p_temp) > 1) {
p <- p_temp
updateSliderInput(inputId = "facet_page", max = n_pages(p_temp))
} else {
p <- plot + facet_wrap(facets, ncol = ncol, nrow = nrow)
}
list(
plot = p,
n_pages = n_pages(p_temp)
)
})
}
# Generate an app with facet page slider UI and server modules for testing and experimentation
facetPageApp <- function() {
ui <- fluidPage(
facetPageUI("facet_page"),
plotOutput("plot")
)
server <- function(input, output, session) {
output$plot <- renderPlot({
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point()
facet_page <- facetPageServer("facet_page", p, c("Species"), ncol = 1, nrow = 1)
facet_page$plot
})
}
shinyApp(ui, server)
}
facetPageApp()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment