shiny

How to write MCVE (Minimal, Complete, and Verifiable example) Shiny apps

Introduction#

If you are having issues with your Shiny apps, it is good practice to create an app that illustrates your point. This app should be as simple as possible while still reflecting your problem. This means using simple datasets, self-explanatory naming (especially for I/O IDs) and replacing plots with simpler ones.

It is also advisable to create your MCVE in a way that as little non-standard libraries as possible are required.

Basic structure

MCVE’s should start the Shiny app when they are copied in the console. An easy way to do this is using the shinyApp function. For example:

why is my checkbox not responding?

library(shiny)

ui <- fluidPage(
  checkboxInput('checkbox', 'click me'),
  verbatimTextOutput('text')
)

server <- function(input, output, session){
  output$text <- renderText({
    isolate(input$checkbox)
  })
}

shinyApp(ui, server)

Alternatively, you can also not assign variables to ui and server.

library(shiny)

shinyApp(
  fluidPage(
    checkboxInput('checkbox', 'click me'),
    verbatimTextOutput('text')
  ),
  function(input, output, session){
    output$text <- renderText({
      isolate(input$checkbox)
    })
  }
)

shinyApp(ui, server)

Avoid unnecessary details

In practice, shiny Apps are often very complicated and full of features that have been developed over time. More often than not, those additional details are not necessary to reproduce your issue. It is best if you skip such details when writing MCVE’s.

WRONG

Why is my plot not showing?

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput('plot')
)

server <- function(input, output, session){
  df <- data.frame(treatment = rep(letters[1:3], times = 3),
                   context = rep(LETTERS[1:3], each = 3),
                   effect = runif(9,0,1))
  df$treat.con <- paste(df$treatment,df$context, sep = ".")
  df$treat.con <- reorder(df$treat.con, -df$effect, )
  output$plot = renderPlot({
    myPlot <- ggplot(df, aes(x = treat.con, y = effect)) +
       geom_point() +
       facet_wrap(~context, 
                  scales = "free_x",
                  ncol = 1)
  })
}

shinyApp(ui, server)

RIGHT

Why is my Plot not showing?

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput('plot')
)

server <- function(input, output, session){
  output$plot = renderPlot({
    myPlot <- ggplot(mtcars, aes(mpg, wt)) + geom_point() 
  })
}

shinyApp(ui, server)

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow