32 Interactive Visualization with Shiny
32.1 Prerequisites
Answer the following questions to see if you can bypass this chapter. You can find the answers at the end of the chapter in Section 32.20.
- What are the two top-level components of every Shiny application?
- What does
reactive()do, and how does its behavior differ from that of a plain R function? - How are outputs wired between the UI and the server in a Shiny application?
32.2 Learning objectives
By the end of this chapter you should be able to:
- Explain Shiny’s reactive programming model: inputs, outputs, reactive expressions, observers.
- Build a single-file Shiny app with
ui,server, andshinyApp(). - Distinguish
reactive()(cached, recomputed on dependency change, used to produce a value) fromobserveEvent()(run for side effects, no cached return value). - Use
bindEvent()(a more general decorator added in Shiny 1.6 alongsideeventReactive()) to control when an expensive reactive recomputes. - Modularize an app using Shiny modules with namespace isolation.
- Deploy an app to
shinyapps.ioor a Posit Connect server. - Debug reactivity with
reactlogand trace through a reactivity graph.
32.3 Orientation
An interactive application lets collaborators explore a model’s behavior without running any code. For a biostatistician, this means writing less one-off code in response to every new question a collaborator asks. A question such as ‘what does the predicted survival look like at age 70?’ becomes a slider on a deployed app rather than a request for a new PDF. Shiny is the dominant tool for building such applications in R.
The framework was created by Joe Cheng at RStudio (now Posit). It has matured over a decade into the standard for analytic dashboards in R. Hadley Wickham’s Mastering Shiny (mastering-shiny.org) is the canonical modern reference.
In this chapter we shall begin with the judgments the statistician brings to an application (Section 32.4) and with a one-page account of the reactive model. We then build a minimal app and examine inputs, outputs, and reactive expressions in turn. The middle sections treat the distinction between reactive() and observeEvent(), the control of expensive recomputation, input validation, and modules. We close with deployment, debugging, a worked regression explorer, and the use of an LLM as a collaborator.
32.4 The statistician’s contribution
Shiny apps appear easy until one has to be maintained. The pitfalls are predictable, but the judgments that prevent them are not part of the framework.
Decide what should be reactive. Every input change can trigger every downstream computation. For a small dataset filter that behavior is appropriate. For a 30-second model fit that runs every time the user moves a slider by 1, it is disastrous. The right reactive granularity is the analyst’s judgment, and the framework will not choose it for us. It often involves bindEvent() to delay expensive computations until a ‘Run’ button is pressed.
Validate inputs. A Shiny app is a public surface, even when ‘public’ means ‘visible to three collaborators’. Suppose that the user uploads a CSV with extra columns, or sets a slider to zero. If such an input crashes the server, that is a bug. validate() and req() catch these cases gracefully.
Modularize. A single-file app of 200 lines is manageable, whereas a single file of 2000 lines is unmaintainable. Shiny modules allow a UI/server pair that handles one component (a dataset selector, a plot, a table) to be encapsulated. Such pairs are then combined with namespace isolation. Splitting the monolith is the difference between an app that survives a year of feature requests and one that gets rewritten.
Be deliberate about deployment. The destinations differ in ways that matter. A shinyapps.io free-tier app times out after idle minutes. A self-hosted Shiny Server has different scaling and security characteristics, and a Posit Connect deployment integrates with internal authentication. The destination should therefore be chosen to match the audience.
32.5 Reactive programming in one page
Shiny’s reactive model has three building blocks:
- Reactive sources. Inputs (
input$x) and external state. They produce values that change over time. - Reactive expressions. Computations that depend on reactive sources. They are lazy (only run when their output is needed) and cached (rerun only when a dependency changes).
- Observers. Computations that run for side effects (writing files, updating an external database). They run whenever a dependency changes and do not return a cached value.
The dependency graph is built automatically. When we write reactive({ filter(data, year == input$year) }), Shiny notes that the expression depends on input$year. When input$year changes, the expression’s cached value is invalidated. The next time anything asks for it, the expression recomputes.
This is a different mental model from imperative R. We do not call functions in order. Instead, we declare relationships and let the framework determine the order of execution. On the plus side, the UI updates automatically when inputs change. On the minus side, bugs concern when things happen, and such bugs are harder to debug than errors in what is computed.
32.6 A minimum Shiny app
library(shiny)
ui <- fluidPage(
titlePanel("Penguin scatter"),
sidebarLayout(
sidebarPanel(
selectInput("xvar", "X variable",
choices = c("flipper_length_mm",
"bill_length_mm",
"body_mass_g")),
selectInput("yvar", "Y variable",
choices = c("body_mass_g",
"bill_depth_mm"))
),
mainPanel(
plotOutput("scatter")
)
)
)
server <- function(input, output, session) {
output$scatter <- renderPlot({
data <- na.omit(palmerpenguins::penguins)
ggplot(data,
aes(.data[[input$xvar]],
.data[[input$yvar]],
colour = species)) +
geom_point() +
theme_minimal()
})
}
shinyApp(ui, server)The reader will note five features of this app.
uiis HTML in disguise.fluidPage,sidebarLayout, and friends are R functions that emit HTML.- Each input has an id and a server-side counterpart.
selectInput("xvar", ...)in the UI corresponds toinput$xvarin the server. - Each output has a UI placeholder and a server
render*function paired by id.plotOutput("scatter")in the UI;output$scatter <- renderPlot({ ... })in the server. renderPlot({ ... })is reactive. It re-runs every time any reactive value referenced in the body changes: here,input$xvarandinput$yvar.shinyApp(ui, server)returns an app object that can be run interactively (in the console) or deployed.
The .data[[input$xvar]] syntax inside aes() lets us use a string-valued input as a data column reference. This is the modern tidy-eval idiom for selecting a column by a character name.
32.7 Inputs, outputs, reactives
Inputs are widgets the user controls:
numericInput,sliderInput,selectInput,checkboxInput,radioButtons.textInput,passwordInput,dateInput,dateRangeInput.fileInputfor uploads,actionButtonfor triggering events.
Outputs are placeholders for content the server fills in:
plotOutput,tableOutput,DT::DTOutput,verbatimTextOutput,textOutput,htmlOutput,uiOutput.
render* functions on the server side populate them:
renderPlot,renderTable,DT::renderDT,renderPrint,renderText,renderUI.
Reactives are intermediate computations:
server <- function(input, output, session) {
# cached intermediate
filtered <- reactive({
data |> filter(year == input$year)
})
# plot uses filtered() (note the parentheses!)
output$plot <- renderPlot({
ggplot(filtered(), aes(x, y)) + geom_point()
})
# table uses the same filtered() value, not recomputed
output$table <- renderTable({
summarise(filtered(), n = n(), mean = mean(y))
})
}The reactive filtered() is shared by both outputs. Without it, filter(data, year == input$year) would run twice. With it, the filter runs once and the cached value is shared.
32.8 reactive() vs observeEvent()
A reactive() produces a value (lazy, cached). An observeEvent() runs for side effects (eager, no cached return value):
# computes a value, used by downstream code
filtered <- reactive({ filter(data, year == input$year) })
# performs an action, no value
observeEvent(input$save_button, {
saveRDS(filtered(), "results.rds")
showNotification("Saved")
})We use reactive() when a cached intermediate value is to be referenced by multiple downstream reactives or outputs. We use observeEvent() when we want to do something because an input changed (or a button was clicked) but do not need a return value.
observe() (without Event) runs whenever any of its dependencies changes. observeEvent(trigger, expr) runs only when trigger changes; expr runs inside isolate(), so reactives it reads do not retrigger it.
32.9 Controlling expensive recomputation
The default reactive model recomputes whenever a dependency changes. For expensive computations (a long model fit, a database query, an external API call), this behavior is unacceptable. The user wants the model to update only after the parameters have been entered.
bindEvent(), added in Shiny 1.6 alongside the older eventReactive(), provides this control:
# expensive fit, only re-runs when run_button is clicked
fit <- bindEvent(reactive({
Sys.sleep(5) # pretend this is expensive
lm(y ~ x, data = filtered())
}), input$run_button)
# fit() returns the most recent fit; before the first
# click it raises a silent validation error, as req() does
output$summary <- renderPrint({ summary(fit()) })For an observeEvent, the syntax is similar:
observeEvent(input$run_button, {
fit <- lm(y ~ x, data = filtered())
saveRDS(fit, "fit.rds")
})The ‘Reactivity in depth’ chapter of Mastering Shiny is essential reading on the question of reactive timing.
32.10 Validating inputs
validate() and req() halt reactive evaluation when inputs are not in valid states:
output$result <- renderPlot({
req(input$file) # need a file
data <- read.csv(input$file$datapath)
validate(
need(nrow(data) > 0, "File is empty"),
need(ncol(data) >= 2, "Need at least 2 columns"),
need(input$xvar %in% names(data), "Selected x variable not present")
)
ggplot(data, aes(.data[[input$xvar]], .data[[input$yvar]])) +
geom_point()
})req(input$file) halts evaluation silently if the user has not yet uploaded a file. In that case nothing renders and no error is shown.
validate(need(...)) halts evaluation and displays a human-readable message explaining why. This is useful when the user has done something that is almost, but not quite, right.
Without these checks, an app with a missing file or invalid input throws server-side errors that may render as red text in the UI or stack traces in the log.
32.11 Shiny modules
A Shiny module is a UI/server pair that handles one component, with its own namespace. Modules are how single-file apps become maintainable multi-file applications.
# module: a dataset selector with a preview table
dataset_ui <- function(id) {
ns <- NS(id)
tagList(
selectInput(ns("dataset"), "Dataset",
choices = c("mtcars", "iris", "penguins")),
tableOutput(ns("preview"))
)
}
dataset_server <- function(id) {
moduleServer(id, function(input, output, session) {
data <- reactive({
switch(input$dataset,
mtcars = mtcars,
iris = iris,
penguins = na.omit(palmerpenguins::penguins))
})
output$preview <- renderTable({ head(data()) })
return(data) # return the reactive for caller to use
})
}
# top-level app uses the module
ui <- fluidPage(
dataset_ui("data1"),
plotOutput("scatter")
)
server <- function(input, output, session) {
data <- dataset_server("data1")
output$scatter <- renderPlot({
ggplot(data(), aes(.data[[names(data())[1]]],
.data[[names(data())[2]]])) +
geom_point()
})
}Modules provide three benefits.
- Namespace isolation.
NS(id)ensures that two instances of the same module do not collide on input ids. - Reusability. A module is defined once and instantiated many times.
- Testability. Each module can be tested in isolation.
For an app larger than a few hundred lines of code, modules are the canonical way to keep the codebase organized.
32.12 Deployment
There are three common destinations.
shinyapps.io is Posit’s hosted service. Its free tier allows a few apps with limited active hours per month. rsconnect::deployApp() deploys with a single call. URLs are public, and basic authentication is available on paid plans.
Posit Connect is the enterprise self-hosted platform. It integrates with internal authentication, scales across multiple servers, and supports private deployments.
Self-hosted Shiny Server (open source) is free, but we then manage the infrastructure ourselves: server provisioning, scaling, authentication, and monitoring. It is the ‘just run a Shiny app on my Linux box’ option.
For deployment to shinyapps.io:
library(rsconnect)
deployApp(appDir = ".", appName = "penguin-explorer",
forceUpdate = TRUE)For each destination the deployment documentation should be read with care. The {rsconnect} package handles the basics. Production deployments, however, often require attention to memory limits, session timeouts, and authentication.
32.13 Debugging reactivity
reactlog::reactlog_enable() records every reactive event. To use it, we run the app, interact with it, and then call reactlog::reactlog_show() to see the dependency graph and event history:
options(shiny.reactlog = TRUE)
runApp("my_app")
# (interact)
reactlog::reactlog_show()The interactive viewer shows which reactives recomputed when, which dependencies triggered which updates, and which observers ran in response to which events. For debugging an app where things update at the wrong time or not at all, reactlog is the canonical tool.
For server-side errors in development, the messages and stack traces print to the R console from which shiny::runApp() was called. For production, the deployment platform’s logs (Posit Connect, shinyapps.io) capture stack traces.
32.14 Worked example: regression explorer
To illustrate, consider an app that fits a linear model to the Palmer penguins data and displays the residuals and the coefficient table.
library(shiny)
library(palmerpenguins)
library(ggplot2)
library(broom)
penguins_clean <- na.omit(penguins)
ui <- fluidPage(
titlePanel("Penguin regression explorer"),
sidebarLayout(
sidebarPanel(
selectInput("response", "Response",
choices = c("body_mass_g",
"bill_length_mm")),
checkboxGroupInput("predictors", "Predictors",
choices = c("flipper_length_mm",
"bill_depth_mm",
"species",
"sex"),
selected = c("flipper_length_mm",
"species")),
actionButton("fit", "Fit")
),
mainPanel(
plotOutput("scatter"),
tableOutput("coefficients")
)
)
)
server <- function(input, output, session) {
formula <- reactive({
req(input$predictors)
as.formula(paste(input$response, "~",
paste(input$predictors, collapse = " + ")))
})
fit <- bindEvent(reactive({
lm(formula(), data = penguins_clean)
}), input$fit)
output$scatter <- renderPlot({
req(fit())
diag <- augment(fit())
ggplot(diag, aes(.fitted, .resid)) +
geom_point() +
geom_smooth(method = "loess", se = FALSE) +
labs(title = "Residuals vs. fitted")
})
output$coefficients <- renderTable({
req(fit())
broom::tidy(fit(), conf.int = TRUE)
})
}
shinyApp(ui, server)The user picks a response and predictors and then clicks ‘Fit’. The fit recomputes only when the button is clicked, not on every checkbox change. The plot and table both share the cached fit(). req() ensures graceful handling before the first fit.
32.15 Collaborating with an LLM on Shiny
On the one hand, LLMs can produce a large amount of working Shiny code quickly. On the other hand, the reactivity bugs in that code are easy to miss.
Prompt 1: drafting an app. We describe the app: what the user should see, which inputs they should have, and what output should appear. We then ask: ‘write a single-file Shiny app implementing this. Use bindEvent() for any expensive computation that should be gated behind a button.’
What to watch for. Apps drafted by an LLM tend by default to be too reactive, so that every input change triggers everything. For expensive computations, gating with bindEvent() / actionButton() is essential.
Verification. We run the app, move the sliders quickly, and see whether the app keeps up. If it stutters, the computation is too aggressive, and we refactor it with bindEvent.
Prompt 2: diagnosing a reactivity bug. We paste the relevant chunk of server code and describe the symptom, for example ‘when I change input X, output Y does not update’ or ‘when I change input X, output Y updates twice’. We then ask the LLM for a diagnosis.
What to watch for. The LLM should recognize common patterns: missing parentheses on a reactive call (fit vs. fit()), observeEvent where reactive was needed, or vice versa. If the diagnosis is generic, we press for specifics.
Verification. We apply the fix and observe whether the bug goes away, using reactlog if the bug is subtle.
Prompt 3: refactoring to modules. We paste the single-file app and ask: ‘refactor this into Shiny modules. Identify reasonable component boundaries.’
What to watch for. The LLM should respect namespace boundaries (using NS(id) consistently). Common errors include forgetting ns() on input ids in the module UI, or using global state that breaks with multiple module instances.
Verification. We run the refactored app. If the module’s input ids are used correctly, instantiating two copies of the module should not cause id collisions.
32.16 Principle in use
Three habits define defensible Shiny development:
- Match reactive granularity to cost. Cheap computations can run on every input change; expensive ones need
bindEvent()and an explicit trigger. - Validate inputs.
req()andvalidate()are a small investment that produces graceful failure modes. - Modularize as the app grows. Single-file apps above a few hundred lines should be split into modules. Modules also enable unit testing.
32.17 Exercises
- Build a Shiny app that lets the user pick a dataset from a drop-down, choose x and y variables, and view a scatter plot. Add a slider for the
loesssmoothing span. - Deploy the app from exercise 1 to shinyapps.io (free tier). Share the URL with a classmate and have them try to break it. Fix whatever they break.
- Convert the app into a two-module design: a
dataset_ui/servermodule for data selection and aplot_ui/servermodule for plotting. Explain why modular code is easier to test. - Add an upload-CSV input that lets the user supply their own data. Add
req()andvalidate()calls so the app handles bad uploads gracefully (empty file, non-CSV file, file with no numeric columns). - Use
reactlogto inspect the dependency graph of your app from exercise 4. Are any reactives being re-evaluated more than necessary? Optimize.
32.18 Further reading
- (Wickham, 2021), Mastering Shiny, the canonical modern reference, free at mastering-shiny.org.
- (Sievert, 2020), interactive graphics with plotly, which pairs naturally with Shiny for dashboards.
- The
shinypackage vignettes, especially ‘Reactivity: An overview’.
32.19 Practice test
The following multiple-choice questions exercise the chapter’s content. Attempt each question before expanding the answer.
32.19.1 Question 1
What are the two main components that make up every Shiny application?
- HTML and JavaScript functions
- User Interface (UI) and Server components
- Input widgets and reactive functions
- Plotly objects and ggplot2 visualizations
B. Every Shiny app is defined by a UI (inputs and output placeholders) and a server (logic computing outputs from inputs).
32.19.2 Question 2
What is the primary purpose of the reactive() function?
- To render graphics that update automatically
- To create user interface elements like sliders or dropdown menus
- To define computations that automatically update when their inputs change, with caching
- To establish a connection between the server and the user’s web browser
C. reactive() caches its value and re-runs only when a reactive dependency changes.
32.19.3 Question 3
How are outputs created in a Shiny application?
- Outputs are created using HTML tags in the UI and do not require server-side processing
- Each output must be created with its own separate
app.Rfile
- Each output must be created with its own separate
- Output functions in the UI must have corresponding render functions in the server, paired by id
- Shiny outputs can only display static content
C. UI output functions (e.g., plotOutput("p")) are paired by id with server render functions (e.g., output$p <- renderPlot({...})).
32.19.4 Question 4
You want a long-running model fit to recompute only when the user clicks a ‘Run’ button. Which Shiny construct implements this?
reactive()alone.
observeEvent(input$run_button, ...)returning a value.
reactive()combined withbindEvent()(or equivalentlyeventReactive()).
isolate().
C. bindEvent() (or its older synonym eventReactive) wraps a reactive so it recomputes only when the named trigger changes.
32.19.5 Question 5
The recommended approach to debugging Shiny reactivity is:
- Add
print()statements throughout the server.
- Add
- Use
reactlog::reactlog_show()to inspect the dependency graph and event history.
- Use
- Run the app in a separate R process and read the log files.
- Avoid reactivity altogether by hardcoding values.
B. reactlog is the canonical tool for tracing which reactives ran when, in response to which events.
32.20 Prerequisites answers
- A user-interface (UI) function and a server function. The UI defines inputs and output placeholders; the server defines how outputs are computed from inputs.
shinyApp(ui, server)ties them into an app object. reactive()wraps a computation so that its value is cached and recomputed only when a reactive dependency (typicallyinput$*or another reactive) changes. A plain R function recomputes every time it is called, regardless of whether its inputs have changed. Reactives are referenced with parentheses (fit()) to retrieve their current value.- Each output placeholder in the UI has a companion
render*()function in the server, paired by a shared id. For example,plotOutput("p")in the UI is populated byoutput$p <- renderPlot({ ... })in the server. Shiny tracks the dependencies of therenderPlotbody and re-runs it whenever a referenced reactive value changes.