Adding motion to choropleths

  • April 2016
  • R

Time ago @hrbrmstr show how to replicate a visualization made by New York Times with R.

The result we hope is like this:

I really like small multiples and this is a good example of usage. However if the multiples means a lot mini plots maybe you can try add animation.

Let’s start using the script made by Bob:

URL <- "http://graphics8.nytimes.com/newsgraphics/2016/01/15/drug-deaths/c23ba79c9c9599a103a8d60e2329be1a9b7d6994/data.json"

data("uscountygeojson")
data("unemployment")

data <-  fromJSON(URL) %>% 
  tbl_df() %>% 
  gather(year, value, -fips) %>% 
  mutate(year = sub("^y", "", year),
         value = ifelse(is.na(value), 0, value))

head(data)
fips year value
01001 2002 1
01003 2002 2
01005 2002 0
01007 2002 1
01009 2002 2
01011 2002 0

Now we’ll prepare the data as the motion plugin require the data.

ds <- data %>% 
  group_by(fips) %>% 
  do(item = list(
    fips = first(.$fips),
    sequence = .$value,
    value = first(.$value))) %>% 
  .$item

hc <- highchart(type = "map") %>% 
  hc_add_series(data = ds,
                name = "drug deaths per 100,000",
                mapData = uscountygeojson,
                joinBy = "fips",
                borderWidth = 0.01) %>% 
  hc_colorAxis(stops = color_stops()) %>%  
  hc_title(text = "How the Epidemic of Drug Overdose Deaths Ripples") %>% 
  hc_legend(layout = "vertical", reversed = TRUE,
            floating = TRUE, align = "right") %>% 
  hc_add_theme(hc_theme_smpl()) %>% 
  hc_motion(
    enabled = TRUE,
    axisLabel = "year",
    labels = sort(unique(data$year)),
    series = 0,
    updateIterval = 50,
    magnet = list(
      round = "floor",
      step = 0.1
    )
  )

And the result:

hc

open

I like it!

Note this using the development version of highcarter using the motion plugin.

comments powered by Disqus