Overview

In this practical you’ll practice creating interactive graphics with shiny.

By the end of this practical, you’ll try to create the app above!

Datasets

File Rows Columns
baselers.csv 260 24
kc_house.csv 21613 21

Packages

Package Installation
tidyverse install.packages("tidyverse")
DT install.packages("DT")

Tasks

A - Getting setup

  1. Open your baselrbootcamp R project.

  2. Create a new folder in your project called 5_Shiny.

  3. Inside of your 5_Shiny folder, create a new folder called 1_Data (not the one you had previously)

  4. In your computer browser, copy and paste the baselers.csv file into your new 1_Data folder.

  5. In RStudio, click File – New File – Shiny Web App

  1. Save the app under the name “Shiny_Baselers” in your 5_Shiny folder:

  1. A new file called app.R should now be open! Click the “Run App” button to open the app.

  1. Your app should now be up in a new window! Play around with the Number of Bins slider to see its effect on the plot

B - Starting with a new template

  1. We have a new app template we’d like you to use. You can find it at this link: Shiny Template - app.R. Open this link and copy all of the code it contains. Then, go back to your app.R file and delete all of the content in the file. After, paste all of the code you just copied.

  2. Click the “Run App” button to run the app! You should now see the following app

  1. Play around with the inputs in the app and click in the different tabs. What content can you change?

C - Add a subtitle

  1. Now it’s time to add a new widget to the user interface! After the existing textInput(inputID = "Title, ...) code, add a single comma (like you see below). Then, just below that in the section where you see # Add subtitle, add the following code:
textInput(inputId = "title",
          label = "Title",
          value = "Plot Title"),   # Add the comma here!!!
      
# Add subtitle

textInput(inputId = "subtitle",
              label = "Subtitle",
              value = "")
  1. Run your app! If you get an error, ask for help!

  2. Do you see the new text input field? Play around with the input. Do you see any changes to the plot? I predict you won’t!

  3. Don’t worry we’ll fix it! We need to change the plotting code to recognize our new input$subtitle input. In the ggplot() code in the server section, change subtitle = "subtitle" to subtitle = input$subtitle like you see below.

labs(title = input$title,
         subtitle = "subtitle",   # Change to: input$subtitle
         x = "age",
         y = "income",
         caption = "My Caption")
  1. Run your app and play around! Does your new subtitle field work now? It should!

D - Add a caption

  1. Now it’s time to add a caption! Using the same logic as above, add a new text input with inputID = "caption" to your user interface. Use the template below for help!
# Add caption
textInput(inputId = "caption",
          label = "Caption",
          value = "")
  1. Update your ggplot() code so that caption = input$caption like below:
labs(title = input$title,
         subtitle = input$subtitle, 
         x = "age",
         y = "income",
         caption = "caption")   # Change to: input$caption
  1. Run your app! Does the new caption text widget work?

E - Add x and y aesthetics

  1. Now it’s time to control which variables are mapped to the x and y aesthetics. To do this, first add the following two new selectInput() widgets to the user interface (below your ‘caption’ input)
# Add this to your ui code!!      

# Add x

selectInput(inputId = "x",
            label = "x",
            choices = names(data)),

# Add y

selectInput(inputId = "y",
            label = "y",
            choices = names(data))
  1. Now it’s time to change the ggplot code so that it sees your new widgets. Replace the exising values of "age" and "income" with input$x and input$y as follows:
 p <- ggplot(data = data,
                aes_string(x = "age",      # Change to: input$x
                           y = "income"))  # Change to: input$y
  1. Run your app! Play around! You should now be able to select your x and y aesthetics!

F - Add color

  1. Time to allow the user to color the points of the plot. To do this, include a new selectInput() as follows:
# Add color

selectInput(inputId = "color",
              label = "Point colors",
              choices = colors(),
              selected = "black"),
  1. In your ggplot code, change col = "black" to col = input$color
p <- ggplot(data = data,
              aes_string(x = input$x, 
                         y = input$y)) + 
    geom_point(alpha = 1, 
               col = "black",     # Change to: input$color
               size = input$size)
  1. Run your app! Can you now change the colors of your points?

G - Add alpha

  1. Using the same logic as above, add a new sliderInput() to the user interface that allows the user to control the alpha level of the points using the following code:
# Add alpha sliderInput to user interface

sliderInput(inputId = "alpha",
            label = "alpha",
            min = 0,
            max = 1,
            value = 1)
  1. In your ggplot() server code, replace alpha = 1 with alpha = input$alpha
geom_point(alpha = 1,             # Change to: input$alpha 
           col = input$color,
           size = input$size) +
  1. Run your app! Can you now control the alpha (transparency) of the points?

H - Add regression line

  1. Now we’ll add a checkbox that allows the user to add a regression line to the plot. First, add the following checkboxInput() to the user interface:
# Add smooth

checkboxInput(inputId = "smooth",
              label = "Add Regression line?",
              value = FALSE)
  1. Next add the following code below the ggplot() code. This will add geom_smooth() to the existing plotting object p
# ggplot() code above...

# ADD smooth
    
# --------------------------

if(input$smooth) {
  
  p <- p + geom_smooth(method = "lm")
  
}

# ---------------------------

# Return the plotting object!

print(p)
  1. Re run your app! Can you now add a regression line to your plot?

I - Add a download plot button

  1. Let’s add a button to download your plot! Start by adding the following downloadButton() input to the user interface.
# Add downloadPlot

downloadButton(outputId = "downloadPlot",
               label = "Download Plot!")
  1. In the server code, add the following code to tell the download button what to do!
# Add output$downloadPlot!

output$downloadPlot <- downloadHandler(
  filename = "myplot.png",
  content = function(file) {
    ggsave(file, plot = my_plot(), device = "png")
  }
)
  1. Run your app! Play around and try your new download button. Did it work!

J - Add a table tab

  1. Now it’s time to add our nice HTML table to your Data tab. Replace the current value tabPanel("Data") with the following:
# Table tab
tabPanel("Data", br(), dataTableOutput("table"))   # Add this!!!
  1. In your server code, add the following block of code. This will send your rendered data table to the user interface.
# Generate a summary of the data ----
output$table <- renderDT({
  
  datatable(data %>%
              select(1:8))
  
})
  1. Run your app! Do you see your new table!

K - Change the dataset!

  1. Because your code is totally flexible, you can easily try your app on a new dataset. Copy the kc_house.csv file into your 1_Data folder inside of your 5_Shiny folder. Then, in your Shiny code, remove the baselers.csv data and replace it with the kc_house.csv data.

  2. Re run the app! Can you now analyse the kc_house.csv data instead of the baselers.csv data?