Intro to
Interactivity
in R

Day 22

Prof Amanda Luby

Carleton College
Stat 220 - Spring 2025

Today

  • RMarkdown outputs
  • Dashboards
  • Intro to interactive toolkit

rmarkdown outputs: pdf

---
title: "Example Document"
author: "Amanda Luby"
date: "2025-02-26"
output:
  pdf_document
---

rmarkdown outputs: html

---
title: "Example Document"
author: "Amanda Luby"
date: "2025-02-26"
output:
  html_document
---

rmarkdown outputs: html, custom theme

---
title: "Example Document"
author: "Amanda Luby"
date: "2025-02-26"
output:
  html_document:
    theme: darkly
---

rmarkdown outputs: github-flavored markdown

---
title: "Example Document"
author: "Amanda Luby"
date: "2025-02-26"
output:
  github_document
---

rmarkdown outputs: html theme in a package

---
title: "Example Document"
author: "Amanda Luby"
date: "2025-02-26"
output:
 prettydoc::html_pretty:
    theme: hpstr
---

Dashboards

library(flexdashboard)
---
title: "Recent Earthquakes in Aotearoa New Zealand"
subtitle: "Of Weak Intensity or Greater"
output: 
  flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

Components of a dashboard

  1. Navigation Bar and Pages — Title and author along with links to sub-pages (if more than one page is defined).

  2. Sidebars, Rows & Columns, and Tabsets — Rows and columns using markdown heading (with optional attributes to control height, width, etc.). Sidebars for interactive inputs. Tabsets to further divide content.

  3. Sections – Sections are containers for cell outputs and free form markdown text. The content of sections typically maps to cells in your notebook or source document.

Rows and columns


Graphs
===================================== 

Column {data-width=650}
-----------------------------------------------------------------------

### Chart 1

Column {data-width=350}
-----------------------------------------------------------------------

### Chart 2

### Chart 3

Sections


Column {data-width=350}
-----------------------------------------------------------------------

### Chart 2

### Chart 3

html Widgets Showcase

Earthquake Explorer + Source Code

Interactive Graphics

Interactive Graphics add dimensions to static visualizations via features that the user controls

Features we’ll focus on in this class:

  • Hovering
    • Display additional information about an observation or group via cursor
  • Changing the representation of the data
    • User decides if they want to see the data in a table or a graph
    • Option to select variables
    • Option to select graph
    • Option to tweak parameters of graphs
  • Filtering/subsetting
    • Allow user to control which subset of the data is shown

Workflow

  1. Start with a static graph, describe what insights it offers, then build up
  2. Demonstrate how the interactive features allow you to obtain additional insight that you would not otherwise be able to
    • Just because you can doesn’t mean you should
  3. Document how to use the features (“click on the drop down menu to choose a variable”)

Explanation \(\to\) Exploration

I like to think of interactive components as somewhere on the “Explanation/Exploration” spectrum

plotly

  • Visualization library for interactive and dynamic web-based graphics

  • Plots work in multiple formats

    • viewer windows
    • R Markdown documents
    • shiny apps

Static plot

gap2021 <- gapminder %>% 
  filter(year == 2021) %>%
  ggplot(aes(x = income, y = life, color = four_regions, size = population)) +
    geom_point() +
  labs(
    x = "GDP per capita",
    y = "Life expectancy",
    color = "Region"
  ) +
  scale_x_continuous(labels = scales::dollar_format()) +
  theme_minimal()

gap2021

Static \(\to\) interactive

library(plotly)
ggplotly(gap2021)

Wouldn’t it be nice if we could see the country name when we hover?

gap2021 <- gapminder %>% 
  filter(year == 2021) %>%
  ggplot(aes(x = income, 
             y = life, 
             color = four_regions, 
             size = population,
             text = country)) +
    geom_point() +
  labs(
    x = "GDP per capita",
    y = "Life expectancy",
    color = "Region"
  ) +
  scale_x_continuous(labels = scales::dollar_format()) +
  theme_minimal()

ggplotly(gap2021)

Wouldn’t it be nice if we could see the country name when we hover?

Wouldn’t it be nice if we could see only the country name when we hover?

ggplotly(gap2021, tooltip = "text")

Your turn

Load the palmerpenguins data set and create a scatterplot of body_mass_g vs. flipper_length_mm from the penguins data set. Use color and shape to specify the species.

Once you have a static graphic you’re happy with, load plotly and convert it to an interactive graphic.

  • What tools tips are included by default?
  • Change the default tooltip to include “Species”
  • (If time) use stringr so that the tooltip shows: “Species: Adelie” instead of just “Adelie”
05:00

Your turn 2

Create a bar chart of species from the penguins data set, then convert it to an interactive bar chart.

  • What tools tips are included by default?
  • What would you change?
03:00

Leaflet

Leaflet

  • Leaflet is a javascript library AND an R package
  • Fully open source
  • Can make chloropleths (non-ggplot-syntax) or proportional symbol maps

Create a default leaflet map

library(leaflet)
m = leaflet() %>% 
  addTiles()
m  

Zoom into a specific lat/long coordinate

m = m %>% setView(-93.1560, 44.4614, zoom = 10)
m

Zoom into a specific lat/long coordinate

m = m %>% setView(-93.1560, 44.4614, zoom = 16)
m

Annotate with markers

m %>% 
  addMarkers(-93.153617, 
            44.462511)

Or add a popup

m %>% 
  addPopups(-93.153617, 
            44.462511, 
            'Here is the <b>Math & Stat Dept</b> <br>')

Your turn

  • Find the names of the 3 islands in penguins
  • Find appropriate lat/long locations for each of the islands in penguins using the internet
  • Create a leaflet map with markers for each island (Tip: Start with the world map with no zoom)
  • Include a popup with the island name
05:00

Data Tables

Printing tables

By default, R prints the tibble using typical code formatting:

gapminder2021
# A tibble: 195 × 17
   country         year  life income population geo   four_regions eight_regions
   <chr>          <dbl> <dbl>  <dbl>      <dbl> <chr> <chr>        <chr>        
 1 Afghanistan     2021  64.3   1990   40800000 afg   asia         asia_west    
 2 Angola          2021  66.1   5980   35000000 ago   africa       africa_sub_s…
 3 Albania         2021  78.8  14700    2870000 alb   europe       europe_east  
 4 Andorra         2021  NA    56500      77500 and   europe       europe_west  
 5 United Arab E…  2021  74.3  65200   10100000 are   asia         asia_west    
 6 Argentina       2021  77    22100   46000000 arg   americas     america_south
 7 Armenia         2021  76.1  13600    2970000 arm   europe       europe_east  
 8 Antigua and B…  2021  76.7  18600      99500 atg   americas     america_north
 9 Australia       2021  83.3  51900   26100000 aus   asia         east_asia_pa…
10 Austria         2021  82.6  55000    9070000 aut   europe       europe_west  
# ℹ 185 more rows
# ℹ 9 more variables: six_regions <chr>, members_oecd_g77 <chr>,
#   Latitude <dbl>, Longitude <dbl>, `UN member since` <chr>,
#   `World bank region` <chr>, `World bank, 4 income groups 2017` <chr>,
#   `World bank, 3 income groups 2017` <chr>, UNHCR <chr>

This is fine for people who are used to looking at R, but not great for public-facing work.

{DT}: DataTables

The R package {DT} provides an R interface to the JavaScript library DataTables. R data objects (matrices or data frames) can be displayed as tables on HTML pages, and DataTables provides filtering, pagination, sorting, and many other features in the tables.

{DT} Example

library(DT)
datatable(gapminder2021)

Remove rownames

datatable(gapminder2021,
          rownames = FALSE)

Add option to filter

datatable(gapminder2021,
          rownames = FALSE,
          filter = "top")

Change font size of text within the table

Otherwise, font options are passed from your html document settings

datatable(gapminder2021,
          rownames = FALSE,
          filter = "top") %>%
  formatStyle(columns = colnames(gapminder), fontSize = '12pt')

Your turn

  • Create a {DT} table of the penguins dataset
  • Add the option to filter, and make the font size 14pt
02:00

Putting it all together

Let’s improve the flexdashboard-example.Rmd Penguins data explorer:

  • Make all graphs plotly’s with appropriate tooltips
  • Replace the data output with your {DT} datatable
  • Include your leaflet map on a new page
  • Add value boxes on the same page as your map that show the number of penguins that live on each island
  • Change the theme of the dashboard