Lab 11 - Interactive Visualization

Learning Goals

  • Read in and process the COVID dataset from the New York Times GitHub repository
  • Create interactive graphs of different types using plot_ly() and ggplotly() functions
  • Customize the hoverinfo and other plot features
  • Create a Choropleth map using plot_geo()

Lab Description

We will work with COVID data downloaded from the New York Times. The dataset consists of COVID-19 cases and deaths in each US state during the course of the COVID epidemic.

The objective of this lab is to explore relationships between cases, deaths, and population sizes of US states, and plot data to demonstrate this

Steps

I. Reading and processing the New York Times (NYT) state-level COVID-19 data

0. Install and load libraries

library(data.table)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.0     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.1     ✔ tibble    3.2.0
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::between()     masks data.table::between()
## ✖ dplyr::filter()      masks stats::filter()
## ✖ dplyr::first()       masks data.table::first()
## ✖ lubridate::hour()    masks data.table::hour()
## ✖ lubridate::isoweek() masks data.table::isoweek()
## ✖ dplyr::lag()         masks stats::lag()
## ✖ dplyr::last()        masks data.table::last()
## ✖ lubridate::mday()    masks data.table::mday()
## ✖ lubridate::minute()  masks data.table::minute()
## ✖ lubridate::month()   masks data.table::month()
## ✖ lubridate::quarter() masks data.table::quarter()
## ✖ lubridate::second()  masks data.table::second()
## ✖ purrr::transpose()   masks data.table::transpose()
## ✖ lubridate::wday()    masks data.table::wday()
## ✖ lubridate::week()    masks data.table::week()
## ✖ lubridate::yday()    masks data.table::yday()
## ✖ lubridate::year()    masks data.table::year()
## ℹ Use the ]8;;http://conflicted.r-lib.org/conflicted package]8;; to force all conflicts to become errors
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(knitr)
library(widgetframe)
## Loading required package: htmlwidgets

1. Read in the data

cv_states_readin <- 
  data.table::fread("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")


state_pops <- data.table::fread("https://raw.githubusercontent.com/COVID19Tracking/associated-data/master/us_census_data/us_census_2018_population_estimates_states.csv")

state_pops$abb <- state_pops$state
state_pops$state <- state_pops$state_name
state_pops$state_name <- NULL

cv_states <- merge(cv_states_readin, state_pops, by = "state")

2. Look at the data

  • Inspect the dimensions, head, and tail of the data
  • Inspect the structure of each variables. Are they in the correct format?
dim(cv_states)
head(cv_states)
tail(cv_states)
str(cv_states)
dplyr::glimpse(cv_states)

3. Format the data

  • Make date into a date variable
  • Make state into a factor variable
  • Order the data first by state, second by date
  • Confirm the variables are now correctly formatted
  • Inspect the range values for each variable. What is the date range? The range of cases and deaths?
cv_states$date <- as.Date(cv_states$date, format = "%Y-%m-%d")

state_list <- unique(cv_states$state)
cv_states$state <- factor(cv_states$state, levels = state_list)
abb_list <- unique(cv_states$abb)
cv_states$abb <- factor(cv_states$abb, levels = abb_list)
# sort by state then date
cv_states <- cv_states[order(cv_states$state, cv_states$date), ]
str(cv_states)
head(cv_states)
tail(cv_states)

summary(cv_states)
min(cv_states$date)
max(cv_states$date)

4. Add new_cases and new_deaths and correct outliers

  • Add variables for new cases, new_cases, and new deaths, new_deaths:
    • Hint: You can set new_cases equal to the difference between cases on date i and date i-1, starting on date i=2
cv_states <- cv_states |>
  group_by(state) |>
  mutate(
    new_cases = c(-999999, diff(cases)),
    new_deaths = c(-999999, diff(deaths))
  ) |>
  mutate(
    new_cases = ifelse(new_cases == -999999, cases, new_cases),
    new_deaths = ifelse(new_deaths == -999999, deaths, new_deaths)
  )
glimpse(cv_states)
## Rows: 58,094
## Columns: 11
## Groups: state [52]
## $ state       <fct> Alabama, Alabama, Alabama, Alabama, Alabama, Alabama, Alab…
## $ date        <date> 2020-03-13, 2020-03-14, 2020-03-15, 2020-03-16, 2020-03-1…
## $ fips        <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ cases       <int> 6, 12, 23, 29, 39, 51, 78, 106, 131, 157, 196, 242, 386, 5…
## $ deaths      <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 4, 4, 5, 11, 14,…
## $ geo_id      <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ population  <int> 4887871, 4887871, 4887871, 4887871, 4887871, 4887871, 4887…
## $ pop_density <dbl> 96.50939, 96.50939, 96.50939, 96.50939, 96.50939, 96.50939…
## $ abb         <fct> AL, AL, AL, AL, AL, AL, AL, AL, AL, AL, AL, AL, AL, AL, AL…
## $ new_cases   <dbl> 6, 6, 11, 6, 10, 12, 27, 28, 25, 26, 39, 46, 144, 152, 101…
## $ new_deaths  <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 0, 1, 6, 3, 1…
  • Filter to dates on or after October 1, 2022
cv_states <- cv_states |>
  dplyr::filter(date >= "2022-10-01")
summary(cv_states$date)
##         Min.      1st Qu.       Median         Mean      3rd Qu.         Max. 
## "2022-10-01" "2022-11-13" "2022-12-26" "2022-12-26" "2023-02-08" "2023-03-23"
  • Use ggplotly for EDA: See if there are outliers or values that don’t make sense for new_cases and new_deaths. Which states and which dates have strange values?
plt_eda_new_cases <- ggplot(
  cv_states, 
  aes(x = date, y = new_cases, colour = state)
) +
  geom_line() +
  theme_minimal()
ggplotly(plt_eda_new_cases)
plt_eda_new_deaths <- ggplot(
  cv_states, 
  aes(x = date, y = new_deaths, colour = state)
) +
  geom_line() +
  theme_minimal()
ggplotly(plt_eda_new_deaths)
  • Correct outliers: Set negative values for new_cases or new_deaths to 0
cv_states <- cv_states |>
  mutate(
    new_cases = ifelse(new_cases > 0, new_cases, 0),
    new_deaths = ifelse(new_deaths < 0, 0, new_deaths)
  )
cv_states |>
  select(new_cases, new_deaths) |>
  summary()
##         state        new_cases         new_deaths      
##  Alabama   : 174   Min.   :    0.0   Min.   :   0.000  
##  Alaska    : 174   1st Qu.:    0.0   1st Qu.:   0.000  
##  Arizona   : 174   Median :    0.0   Median :   0.000  
##  Arkansas  : 174   Mean   :  864.3   Mean   :   8.926  
##  California: 174   3rd Qu.:  423.0   3rd Qu.:   3.000  
##  Colorado  : 174   Max.   :87445.0   Max.   :3732.000  
##  (Other)   :8004
  • Inspect data again interactively
plt_eda_new_cases_2 <- ggplot(
  cv_states, 
  aes(x = date, y = new_cases, colour = state)
) +
  geom_line() +
  theme_minimal()
ggplotly(plt_eda_new_cases_2)
plt_eda_new_deaths_2 <- ggplot(
  cv_states, 
  aes(x = date, y = new_deaths, colour = state)
) +
  geom_line() +
  theme_minimal()
ggplotly(plt_eda_new_deaths_2)

The new death count for New York on November 11, 2022 seem out of place. We can check the counts surrounding the date for New York State. In this case, it doesn’t reveal any obvious error and we will keep the record as is.

cv_states |>
  dplyr::filter(
    state == "New York", 
    between(date, as.Date("2022-11-09"), as.Date("2022-11-12"))
  ) |>
  select(date, cases, new_cases, deaths, new_deaths)
## # A tibble: 4 × 6
## # Groups:   state [1]
##   state    date         cases new_cases deaths new_deaths
##   <fct>    <date>       <int>     <dbl>  <int>      <dbl>
## 1 New York 2022-11-09 6280581      6256  72667         48
## 2 New York 2022-11-10 6286317      5736  72674          7
## 3 New York 2022-11-11 6288122      1805  76406       3732
## 4 New York 2022-11-12 6289735      1613  76406          0

5. Add additional variables

  • Add population-normalized (by 100,000) variables for each variable type (rounded to 1 decimal place). Make sure the variables you calculate are in the correct format (numeric). You can use the following variable names:
    • per100k = cases per 100,000 population
    • newper100k= new cases per 100,000
    • deathsper100k = deaths per 100,000
    • newdeathsper100k = new deaths per 100,000
cv_states <- cv_states |>
  mutate(
    per100k = round(cases / population * 1e5, digits = 1),
    newper100k = round(new_cases / population * 1e5, digits = 1),
    deathsper100k = round(deaths / population * 1e5, 1),
    newdeathsper100k = round(new_deaths / population * 1e5, 1)
  )
cv_states |>
  select(per100k, newper100k, deathsper100k, newdeathsper100k) |>
  summary()
##         state         per100k        newper100k     deathsper100k  
##  Alabama   : 174   Min.   :20691   Min.   :  0.00   Min.   :114.8  
##  Alaska    : 174   1st Qu.:27805   1st Qu.:  0.00   1st Qu.:256.0  
##  Arizona   : 174   Median :30724   Median :  0.00   Median :337.6  
##  Arkansas  : 174   Mean   :30519   Mean   : 13.17   Mean   :320.5  
##  California: 174   3rd Qu.:33170   3rd Qu.: 11.82   3rd Qu.:391.7  
##  Colorado  : 174   Max.   :43676   Max.   :545.90   Max.   :462.8  
##  (Other)   :8004                                                   
##  newdeathsper100k 
##  Min.   : 0.0000  
##  1st Qu.: 0.0000  
##  Median : 0.0000  
##  Mean   : 0.1388  
##  3rd Qu.: 0.1000  
##  Max.   :19.4000  
## 
  • Add a “naive CFR” (case fatality rate) variable representing deaths / cases on each date for each state
cv_states <- cv_states |>
  mutate(
    naive_cfr = deaths / cases
  )
  • Create a dataframe representing values on the most recent date, cv_states_today
max_date <- max(cv_states$date)
cv_states_today <- cv_states |>
  dplyr::filter(date == max_date)

II. Scatterplots

6. Explore scatterplots using plot_ly()

  • Create a scatterplot using plot_ly() representing pop_density vs. various variables (e.g. cases, per100k, deaths, deathsper100k) for each state on most recent date (cv_states_today)
    • Color points by state and size points by state population
    • Use hover to identify any outliers.
plot_ly(
  cv_states_today,
  x = ~ pop_density,
  y = ~ per100k,
  color = ~ state,
  size = ~ population,
  type = "scatter",
  sizes = c(5, 1000),
  marker = list(sizemode = "area", opacity = .8)
)
  • Remove those outliers and replot.
cv_states_today |>
  filter(
    ! state %in% c(
      # "Alaska",
      # "Rhode Island",
      "District of Columbia"
    )
  ) |>
  plot_ly(
    x = ~ pop_density,
    y = ~ per100k,
    color = ~ state,
    size = ~ population,
    type = "scatter",
    sizes = c(5, 1000),
    marker = list(sizemode = "area", opacity = .8)
  )

(Alternatively, use log transfromation)

plot_ly(
  cv_states_today,
  x = ~ log(pop_density),
  y = ~ per100k,
  color = ~ state,
  size = ~ deathsper100k,
  type = "scatter",
  sizes = c(5, 500),
  marker = list(sizemode = "area", opacity = .8)
)
  • Choose one plot. For this plot:
    • Add hoverinfo specifying the state name, cases per 100k, and deaths per 100k, similarly to how we did this in the lecture notes
    • Add layout information to title the chart and the axes
    • Enable hovermode = "compare" hovermode = "x"
plot_ly(
  cv_states_today,
  x = ~ log(pop_density),
  y = ~ per100k,
  color = ~ state,
  size = ~ deathsper100k,
  type = "scatter",
  sizes = c(5, 500),
  marker = list(sizemode = "area", opacity = .8),
  hoverinfo = "text",
  text = ~ paste0(
    state, "\n",
    "  Cases per 100k: ", per100k, "\n",
    "  Deaths per 100k: ", deathsper100k, "\n",
    "  Population density: ", round(pop_density, 1), 
    " per sq miles"
  )
) |>
  layout(hovermode = "x") # compares states with similair x values on hover

7. Explore scatterplot trend interactively using ggplotly() and geom_smooth()

  • For pop_density vs. newdeathsper100k create a chart with the same variables using gglot_ly()
  • Explore the pattern between \(x\) and \(y\)
  • Explain what you see. Do you think pop_density correlates with newdeathsper100k?
plt_smooth <- ggplot(
  cv_states_today,
  aes(x = pop_density, y = newdeathsper100k)
) +
  theme_minimal() +
  geom_smooth() +
  geom_point(aes(colour = state, size = population)) +
  scale_x_continuous(
    trans = "log", 
    breaks = c(1, 10, 100, 1000, 10000),
    labels = c(1, 10, 100, 1000, 10000)
  )
ggplotly(plt_smooth)
# removing District of Columbia without log transformation
plt_smooth <- ggplot(
  cv_states_today |> filter(state != "District of Columbia"),
  aes(x = pop_density, y = newdeathsper100k)
) +
  theme_minimal() +
  geom_smooth() +
  geom_point(aes(colour = state, size = population)) 
ggplotly(plt_smooth)

8. Multiple line chart

  • Create a line chart of the naive_CFR for all states over time using plot_ly()
    • Use the zoom and pan tools to inspect the naive_CFR for the states that had an increase in November How have they changed over time?
plot_ly(
  cv_states,
  x = ~ date,
  y = ~ naive_cfr,
  color = ~ state,
  mode = "lines"
)
  • Create one more line chart, for Florida only, which shows new_cases and new_deaths together in one plot. Hint: use add_lines()
    • Use hoverinfo to “eyeball” the approximate peak of deaths and peak of cases. What is the time delay between the peak of cases and the peak of deaths?
# using add_lines() for both new cases and new deaths displayed both traces.
cv_states |>
  filter(state == "Florida") |>
  plot_ly() |>
  add_lines(
    x = ~ date,
    y = ~ new_cases,
    color = "New Cases"
  ) |>
  add_lines(
    x = ~ date,
    y = ~ new_deaths,
    color = "New Deaths"
  )
# checking other states
cv_states |>
  filter(state == "New York") |>
  plot_ly() |>
  add_lines(
    x = ~ date,
    y = ~ new_cases,
    color = "New Cases"
  ) |>
  add_lines(
    x = ~ date,
    y = ~ new_deaths,
    color = "New Deaths"
  )

9. Heatmaps

Create a heatmap to visualize new_cases for each state on each date greater than January 1st, 2023 - Start by mapping selected features in the dataframe into a matrix using the tidyr package function pivot_wider(), naming the rows and columns, as done in the lecture notes - Use plot_ly() to create a heatmap out of this matrix. Which states stand out?

cv_states_mat <- cv_states |>
  # filter(date >= "2023-01-01") |> # I will include from Oct, 2022
  select(state, date, new_cases) |>
  pivot_wider(names_from = state, values_from = new_cases) |>
  column_to_rownames("date") |>
  as.matrix()
plot_ly(
  x = rownames(cv_states_mat),
  y = colnames(cv_states_mat),
  z = cv_states_mat,
  type = "heatmap",
  colors = "Greys",
  showscale = TRUE
) |>
  colorbar(title = "New cases")
  • Create a second heatmap in which the pattern of new_cases for each state over time becomes more clear by filtering to only look at dates every two weeks.
#create heatmap
filter_dates <- seq(
  as.Date("2022-10-01"),
  max_date,
  by = "2 weeks"
)

cv_states_mat_2 <- cv_states |>
  filter(date %in% filter_dates) |>
  select(state, date, new_cases) |>
  # the column and row were incorrectly placed in tutorial
  pivot_wider(names_from = date, values_from = new_cases) |>
  column_to_rownames("state") |> 
  as.matrix() 

plot_ly(
  x = colnames(cv_states_mat_2),
  y = rownames(cv_states_mat_2),
  z = ~ cv_states_mat_2,
  colors = "Greys",
  type = "heatmap",
  showscale = TRUE
) |>
  colorbar(title = "New cases")
# instead of filtering, we can try averaging every 2 weeks to avoid losing information
# state names are moved to hover instead of showing on the y axis
cv_states_2_week_avg <- cv_states |>
  mutate(week2 = year(date) + round(week(date) / 2, 0)) |>
  group_by(state, week2) |>
  summarise(
    date = min(date), 
    new_cases = mean(new_cases),
    .groups = "drop"
  ) |>
  arrange(state, date, new_cases)
cv_states_mat_3 <- cv_states_2_week_avg |>
  select(state, date, new_cases) |>
  pivot_wider(names_from = date, values_from = new_cases) |>
  column_to_rownames("state") |>
  as.matrix()
hovertext <- cv_states_2_week_avg |>
  mutate(
    hovertext = paste0(state, ", ", 
                       strftime(date, format = "%b %d, %Y"), "\n",
                       "2-week average new cases: ", round(new_cases, 1))) |>
  select(state, date, hovertext) |>
  pivot_wider(names_from = date, values_from = hovertext) |>
  column_to_rownames("state") |>
  as.matrix()

plot_ly(
  x = colnames(cv_states_mat_3),
  z = cv_states_mat_3,
  colors = "Greys",
  type = "heatmap",
  hoverinfo = "text",
  text = hovertext
) |>
  colorbar(title = "New cases") |>
  layout(
    yaxis = list(showticklabels = FALSE, ticklen = 0, title = "States")
  )

10. Map

  • Create a map to visualize the naive_CFR by state on March 15, 2023
pick.date = "2023-03-15"
# Create the map
cv_march_15 <- cv_states |>
  dplyr::filter(date == pick.date)

map_march_15 <- plot_geo(
  cv_march_15,
  locationmode = "USA-states"
) |>
  add_trace(
    z = ~ naive_cfr,
    locations = ~ abb,
    coloraxis = "coloraxis"
  ) |>
  layout(
    geo = list(
      scope = "usa",
      showlakes = TRUE,
      lakecolor = toRGB("steelblue")
    ),
    xaxis = list(title = "March 15, 2023")
  ) |>
  colorbar(
    title = "Naive CFR"
  )
  • Compare with a map visualizing the naive_CFR by state on most recent date
# Map for today's date
map_today <- plot_geo(
  cv_states_today,
  locationmode = "USA-states"
) |>
  add_trace(
    z = ~ naive_cfr,
    locations = ~ abb,
    coloraxis = "coloraxis"
  ) |>
  layout(
    geo = list(
      scope = "usa",
      showlakes = TRUE,
      lakecolor = toRGB("steelblue")
    ),
    xaxis = list(title = strftime(max_date, "%B %d, %Y"))
  ) |>
  colorbar(
    title = "Naive CFR"
  )
# March 15, 2021 for comparison
pick.date = "2021-03-15"
# Create the map
map_2021 <- merge(cv_states_readin, state_pops, by = "state") |>
  dplyr::filter(date == pick.date) |>
  dplyr::mutate(
    date = as.Date(date, format = "%Y-%m-%d"),
    naive_cfr = cases / deaths
  ) |>
  plot_geo(
    locationmode = "USA-states"
  ) |>
  add_trace(
    z = ~ naive_cfr,
    locations = ~ abb,
    coloraxis = "coloraxis"
  ) |>
  layout(
    geo = list(
      scope = "usa",
      showlakes = TRUE,
      lakecolor = toRGB("steelblue")
    ),
    xaxis = list(title = "March 15, 2021", visible = TRUE)
  ) |>
  colorbar(
    title = "Naive CFR"
  )
# subplots with subtitles
# see: https://plotly.com/r/subplots/
titles <- list(
  list( 
    x = 0.5,  
    y = 1.0,  
    text = "March 15, 2021",  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  ),  
  list( 
    x = 0.5,  
    y = .63,  
    text = "March 15, 2023",  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  ),  
  list( 
    x = 0.5,  
    y = .3,  
    text = strftime(max_date, "%B %d, %Y"),  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  )
)
subplot(map_2021, map_march_15, map_today, nrows = 3) |>
  layout(coloraxis = list(colorscale = "Viridis"),
         xaxis = list(visible = TRUE),
         annotations = titles)