Skip to content

Instantly share code, notes, and snippets.

@Patrikios
Last active April 16, 2023 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Patrikios/a0b4b7c768e1c942afca48f12f3a4aeb to your computer and use it in GitHub Desktop.
Save Patrikios/a0b4b7c768e1c942afca48f12f3a4aeb to your computer and use it in GitHub Desktop.
R Shiny modal outputs render on input change strategies (previously rendered plot on input change visible VS plot render does not show previoous plot)
# This app.R demonstrates how R Shiny rerenders a unique output id
# the previously renred plot is initially visible, afterwards changed
# that is how shiny is designed to work
library(shiny)
library(ggplot2)
app <- shinyApp(
ui = fluidPage(
selectInput(
"species",
"Select spiecies",
sort(unique(iris$Species)),
"virginica"
)
),
server = function(input, output) {
observeEvent(input$species, {
showModal(
modalDialog(
textOutput("heading"),
plotOutput("plot"),
easyClose = TRUE,
footer = NULL
)
)
})
output$heading <- renderText(input$species)
output$plot <- renderPlot({
ggplot(subset(iris, Species == input$species)) +
geom_point(aes(Sepal.Length, Sepal.Width))
})
}
)
runApp(app)
# if one wants not the previously displayed plot to initially reapear and then render the new plot
# one can crate with dedicated output ids for each of the plots (bound to the input).
library(shiny)
library(ggplot2)
species <- levels(iris$Species)
app <- shinyApp(
ui = fluidPage(
selectInput(
"species", "Select spiecies", species, "virginica"
)
),
server = function(input, output) {
observeEvent(input$species, {
showModal(
modalDialog(
plotOutput(input$species),
easyClose = TRUE,
footer = NULL
)
)
})
lapply(species, function(x) {
output[[x]] <- renderPlot({
ggplot(subset(iris, Species == x)) +
geom_point(aes(Sepal.Length, Sepal.Width))
})
})
}
)
runApp(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment