2022-12-01

Week 3 assignment: Developing Data Products

Author: FG

Date: December 1, 2022

Plotly allows for nice maps: https://plotly.com/r/choropleth-maps/.

Data for this visualization is from the {datasets} package in R:

  • state.abb: 2-letter abbreviations for the state names
  • state.x77: US State Facts and Figures

Two steps are fundamental:

  • setup the map options on a list for the geo argument in the layout() function
  • specify location,locationmode and type = 'choropleth' in the plot.ly() function

Code for making the map with plotly

library(tidyverse)
library(plotly)
# Create data frame
state_le <- data.frame(
  State = state.abb, 
  Le = as.vector(state.x77[,4])) %>%
  mutate(
    hover=paste(
      State, '<br>', "Life expectancy:", Le))

# Set up some mapping options
map_options <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showlakes = TRUE,
  lakecolor = toRGB('#98c7d0')
)







# Make state borders white
borders <- list(color = toRGB("grey70"))




plot_ly(z = ~state_le$Le, 
        text = ~state_le$hover, 
        locations = ~state_le$State, 
        type = 'choropleth', 
        locationmode = 'USA-states', 
        color = state_le$Le, 
        marker = list(line = borders)) %>%
  layout(
    title='US Life expectancy in years (1969–71)', 
    geo = map_options)

Plotly visualization