• Illumined Insights
  • Posts
  • Shiny Apps in R: An Introduction to Building Interactive Data Visualizations

Shiny Apps in R: An Introduction to Building Interactive Data Visualizations

Part 1: Getting Started with Shiny and RStudio

Welcome to the “Illumined Insights” newsletter! Thank you so much for subscribing. This newsletter touches on all things analytics and data science with a focus on areas such as data visualization and sports analytics. This week we start a series on the development of Shiny applications. Shiny is an R package that allows us to create interactive, web-based applications. I’m no Shiny expert, but have had some experience building some simple apps. Let’s take a look at Shiny!

Stephen Hill, Ph.D.

Are you looking for a way to create interactive data visualizations and dashboards in R? Look no further than Shiny, a powerful web application framework for R. With Shiny, you can build custom web applications that allow users to interact with data and see results in real-time.

In this series of articles, we'll cover the basics of building Shiny apps in RStudio, from setting up your development environment to deploying your app to the web. In this first installment, we'll get you started with the basics of Shiny and RStudio.

Getting Started with Shiny and RStudio

First things first, you'll need to install and set up R and RStudio on your computer. Install R first (download from here) if you haven’t already done so. Next, you’ll need to head to the RStudio website and download the latest version of RStudio (download from here). Both R and RStudio are free. Once you've got R and RStudio set up, you'll need to install the Shiny package in R by typing: “install.packages("shiny")” into the R console. Be patient. It may take a moment for the package to install.

Building a Basic Shiny Application

Now that you've got RStudio and Shiny installed, it's time to start building your first Shiny app. In Shiny, an app consists of two parts: a user interface (UI) and a server. The UI defines how the app looks and what components are available for user interaction, while the server defines how the app responds to user input and generates output. These two elements are contained in a single R script file called “app.R”. Create this file in RStudio by navigating to the “File” menu, “New File”, and then “Shiny Web App”. Give your Shiny application an appropriate name (I’ll use “PenguinExplore1” for mine; you’ll see why later) and click “Create”.

Your “app.R” is prepopulated with some demonstration code. Take a moment to examine the structure of this code. Any R libraries that we need should be at the beginning of the code. In this demo code, the only necessary library is “shiny”. Let’s go ahead and select all of this demo code and delete it. We’ll start with a blank “app.R” file.

Let’s add our libraries. For this work we’ll use three libraries: “shiny”, “tidyverse”, and “palmerpenguins”. The “palmerpenguins” package provides access to a dataset of penguin characteristics and serves as an excellent alternative to the “iris” dataset.

Add these three lines of code to the top of your blank “app.R” file:

library(shiny)
library(tidyverse)
library(palmerpenguins)

If you have not already installed “tidyverse” and “palmerpenguins” you may be prompted to do so. You should go ahead and do this installation. Next, let’s build our app’s user interface. Below the library code, add the following:

ui <- fluidPage(
  titlePanel("Palmer Penguins Explorer"),
  sidebarLayout(
    sidebarPanel(
      selectInput("species", label = "Penguin species:",
                  choices = unique(penguins$species)),
      selectInput("x_var", label = "X-axis variable:",
                  choices = names(penguins)[4:7]),
      selectInput("y_var", label = "Y-axis variable:",
                  choices = names(penguins)[4:7]),
      sliderInput("size", label = "Point size:",
                  min = 1, max = 10, value = 5)
    ),
    mainPanel(
      plotOutput("penguin_plot")
    )
  )
)

‘We start by defining an object called “ui”. This will be our user interface. There are a variety of UI options that we could choose, but a very common one is “fluidPage”. A “fluidPage” layout will automatically adjust how the application is displayed in order to fit the size of the user's screen, making it suitable for use on both desktop and mobile devices. It uses a grid system to specify the placement and sizing of the app's elements, allowing the you to easily create complex and dynamic layouts.

Within the “fluidPage” layout, we can define layout elements. The first element is a “titlePanel”. We’ll give our application a title of “Palmer Penguins Explorer” since that’s the basic gist of what our application will be designed to do (visually explore the Palmer Penguins dataset). Next, we indicate that we want to use a “sidebarLayout” with a “sidebarPanel”. Within the sidebar panel we’ll give our application users four input options. The first three inputs are dropdowns to allow for the selection of penguin species, a penguin characteristic to plot on the x axis of our chart, and a penguin characteristics to plot on the y axis of our chart. The fourth input is a slider to choose the size of the points in our plot. The first element of each input is the name of the input. We’ll keep these input names in mind as we’ll need to reference them in the server part of our code.

The last part of our UI layout is the “mainPanel”. This portion of the layout will hold our plot that is influenced by the user’s input choices. We specify that the output in the main panel will be a plot with a name of “penguin_plot”. Be careful with parentheses. At this point, we have configured the structure of an application layout that will look something like this:

Shiny application layout structure

Next we set-up our server. We’ll use the code below to define how our server handles inputs (from the UI) and provides outputs (to be displayed in the UI).

server <- function(input, output) {
  
  output$penguin_plot <- renderPlot({
    filtered_data <- penguins %>%
      filter(species == input$species)
    
  ggplot(filtered_data, aes_string(x = input$x_var, y = input$y_var)) +
      geom_point(alpha = 0.5, size = input$size, color = "steelblue") +
      ggtitle(paste(input$x_var, "vs.", input$y_var, "for", input$species)) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5))
  })
}

Within our server code, we begin by defining our output object. Our output is a plot that is driven by the input choices made by our user in the UI. We’ll call this output “output$penguin_plot”. The “penguin_plot” part of the naming corresponds to name of the “plotOutput” that we defined in our UI. This output is generated by the “renderPlot” function.

Within the “renderPlot” we begin by filtering the “penguins” dataframe based on the species selected by the user. Notice how the “species” value from the UI is accessed in the server with “input$species”. Next, we use this filtered data in a “ggplot” function to create a scatterplot on the user-selected x and y variables with the user-selected point size. We use a little “ggplot” magic to ensure that our plot is titled correctly and dynamically.

The last element of our Shiny application code ties the UI and server code together:

shinyApp(ui, server)
Running Your Shiny Application Locally

With our application code complete we can now run the application locally and see how well it works. Click “Run App” (shown in the screenshot below") to run the application.

Run the Shiny application locally

Your application should look something like this:

“Palmer Penguins Explorer” Shiny application

You can interact with the application via the dropdown inputs and the slider. Notice how the plot changes in response to your inputs. Once you’re done exploring the application, you can simply close out the application window to shut the application down. If you’re feeling bold, you can try to change some of the elements of the application code and see how those changes are reflected when the application is run.

In Part 2 of the series, we’ll incorporate additional features into our basic Shiny app and discuss how to publish the application online to shinyapps.io. If you want to explore the published version of the application that we’ve just built, you can visit: https://technocat.shinyapps.io/PenguinExplore1/.

How would you use Shiny to develop interactive applications?

Are you interested in learning more about data visualization using R? Click below to get notified about my upcoming book “Data Visualization in R”.

Each week we’ll feature a dataset that we find interesting, useful, etc. This week we highlight another classic R dataset: “gapminder”. This package provides life expectancy, GDP per capita, and population data by country for over 50 years. This is a tremendous dataset to explore and practice your data visualization skills. You could even build a Shiny app to explore this data!

To access the “gapminder” data, visit the link below:

Feedback?

Did you enjoy this week’s newsletter? Do you have a topic, tool, or technique that you would like to see featured in a future edition? I’d love to hear from you!

Support the Newsletter?

Support this newsletter with a “coffee” (optional, but appreciated).

Start Your Own Newsletter?

This newsletter is created on and distributed via Beehiiv, the world’s best newsletter platform. Want to start your own newsletter? Click below to get started. Please note that this is an affiliate link. I may receive a small commission if you sign up for Beehiiv via this link.