Shiny Apps

September 22, 2024

Shiny App

Elements of a Shiny App


  • User interface (UI)
  • Server object
  • Call to ShinyApp

Reactivity


The ability to change the user interface based on user-selected input values.


Reactivity works by having R functions that update different parts of the app when they get new values from the user.

Setup


# load packages
library(shiny)
library(readr)
library(ggplot2)

# load the data 
dem_data <- read_csv("dem_data.csv")

# create list of named values for the input selection
vars <- c("Democracy" = "polyarchy",
          "Clientelism" = "clientelism",
          "Corruption" = "corruption",
          "Women's Empowerment" = "womens_emp",
          "Wealth" = "gdp_pc",
          "Infant Mortality" = "inf_mort",
          "Life Expectancy" = "life_exp", 
          "Education" = "education")

UI


# Define UI for application that draws a scatter plot
ui <- fluidPage(

    # Application title
    titlePanel("Democracy and Development"),

    # Sidebar with a two dropdown menus
    sidebarLayout(
      sidebarPanel(
        selectInput(input = 'xcol', label = 'X Variable', choices = vars),
        selectInput(input = 'ycol', label = 'Y Variable', 
                    choices = vars, selected = vars[[6]])
      ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("scatterplot")
        )
    )
)

Server


# Define server logic required to draw a scatter plot
server <- function(input, output, session) {
  
  # Render the plot
  output$scatterplot <- renderPlot({
    
    # ggplot call
    ggplot(dem_data, aes(x = get(input$xcol), y = get(input$ycol))) +
      geom_point(aes(color = region)) +
      geom_smooth(method = "loess") +
      scale_color_viridis_d(option = "plasma") +
      theme_minimal() +
      labs(
        x =  names(vars[which(vars == input$xcol)]), # select names in vars that
        y =  names(vars[which(vars == input$ycol)]), # match input selections
        caption = "Source: V-Dem Institute",
        color = "Region"
      )
  })
}

Shiny App Call


# See above for the definitions of ui and server
ui <- ...

server <- ...

# Run the application 
shinyApp(ui = ui, server = server)

Your Turn!


  • Do pre-work and wrangling from module 5.1
  • Create new Shiny App file
  • Copy UI, server and Shiny App call
  • See if you can get the app to run locally
10:00

Try on shinyapps.io


10:00

Modify App


  • Try selecting different V-Dem variables
  • Or add some World Bank data
  • Make a new scatter plot or a different visualization
  • Make adjustments to menus
  • Run and publish new app
15:00