Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Created July 16, 2024 09:20
Show Gist options
  • Save matt-dray/702c9de538f8e04e75d0049322cbf619 to your computer and use it in GitHub Desktop.
Save matt-dray/702c9de538f8e04e75d0049322cbf619 to your computer and use it in GitHub Desktop.
Quick demo Shiny app with {bslib} using select inputs and checkbox
set.seed(123)
n <- 5
scheme <- paste("Scheme", 1:n)
mitigator <- paste("Mitigator", LETTERS[1:n])
combos <- tidyr::crossing(scheme, mitigator)
nrows <- nrow(combos)
dat <- combos |>
dplyr::mutate(
lo = runif(nrows),
hi = pmin(lo + runif(nrows, 0.25, 0.5), 1),
mid = (lo + hi) / 2,
years = sample(20:30, nrows, replace = TRUE)
)
ui <- bslib::page_sidebar(
title = "Test facets",
sidebar = bslib::sidebar(
shiny::selectInput(
inputId = "schemes",
label = "Select schemes",
choices = dat$scheme,
selected = paste("Scheme", 1:3),
multiple = TRUE
),
shiny::selectInput(
inputId = "mitigators",
label = "Select mitigators",
choices = dat$mitigator,
selected = paste("Mitigator", LETTERS[1:3]),
multiple = TRUE
),
shiny::checkboxInput(
inputId = "toggle_horizon",
label = "Standardise by horizon length?",
value = FALSE
)
),
bslib::card(
bslib::card_header("Plot"),
shiny::plotOutput("p"),
full_screen = TRUE
)
)
server <- function(input, output) {
dat_selected <- reactive({
shiny::validate(
need(input$schemes, message = "Select at least one scheme."))
shiny::validate(
need(input$mitigators, message = "Select at least one mitigator.")
)
if (input$toggle_horizon) {
dat <- dat |> dplyr::mutate(dplyr::across(c(lo, hi, mid), \(x) x / years))
}
dat |>
dplyr::filter(
scheme %in% input$schemes,
mitigator %in% input$mitigators
)
})
output$p <- shiny::renderPlot({
dat_selected() |>
ggplot2::ggplot() +
ggplot2::geom_pointrange(
ggplot2::aes(x = mid, y = scheme, xmin = lo, xmax = hi)
) +
ggplot2::labs(x = "80% Confidence Interval") +
ggplot2::facet_grid(~mitigator) +
ggplot2::theme_bw(base_size = 20) +
ggplot2::theme(axis.title.y = ggplot2::element_blank())
})
}
shiny::shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment