Interactive reporting + visualization with Shiny I

Lecture 20

Dr. Greg Chism

University of Arizona
INFO 526 - Fall 2024

Announcements

  • Peer evals will be in two-weeks (survey to be announced soon)

Setup

# load packages
if(!require(pacman))
  install.packages("pacman")

pacman::p_load(countdown,
               tidyverse,
               shiny)

# set theme for ggplot2
ggplot2::theme_set(ggplot2::theme_minimal(base_size = 14))

# set width of code output
options(width = 65)

# set figure parameters for knitr
knitr::opts_chunk$set(
  fig.width = 7, # 7" width
  fig.asp = 0.618, # the golden ratio
  fig.retina = 3, # dpi multiplier for displaying HTML output on retina
  fig.align = "center", # center align figures
  dpi = 300 # higher dpi, sharper image
)

Shiny: High level view

Shiny

Every Shiny app has a webpage that the user visits,
and behind this webpage there is a computer that serves this webpage by running R.

Shiny

When running your app locally, the computer serving your app is your computer.

Shiny

When your app is deployed, the computer serving your app is a web server.

Shiny

Demo

  • Clone the shiny-ex repo.
  • Launch the app by opening the app.R file and clicking on Run App.
  • Close the app by clicking the stop icon
  • Select view mode in the drop down menu next to Run App

Anatomy of a Shiny app

What’s in an app?

library(shiny)
ui <- fluidPage()


server <- function(
    input, 
    output, 
    session) {
  ...
}


shinyApp(
  ui = ui, 
  server = server
  )
  • User interface controls the layout and appearance of app

  • Server function contains instructions needed to build app

Data: Health expenditure vs. life expectancy

Source: World Bank and googleCharts

Data: healthexp.Rds

health <- readRDS(here::here("slides/20", "data/healthexp.Rds"))
health |> glimpse()
Rows: 3,030
Columns: 6
$ Country            <fct> "Albania", "Algeria", "Angola", "Arg…
$ Region             <chr> "Europe & Central Asia", "Middle Eas…
$ Year               <dbl> 1995, 1995, 1995, 1995, 1995, 1995, …
$ Population         <dbl> 3141102, 28291591, 12105105, 3485516…
$ Life.Expectancy    <dbl> 71.87029, 68.46588, 42.05093, 72.623…
$ Health.Expenditure <dbl> 28.22459, 62.05589, 20.74863, 615.41…

Ultimate goal

Interactive reporting with Shiny

Livecoding