Opioid Epidemic

I came across the visualization of US opioid epidemic made by Kieran Healy in his book “Data Visualization: A Practical Introduction” (Link). He has used data through 2014 but in recent years the epidemic has become worse. So I extended the data to 2017 by downloading it from Kaiser Family Foundation’s website. After cleaning up the data, I ended up with an unbalanced panel of 50 states over 1999 to 2017.

Next, I wanted to create an animation to better capture the severity of the epidemic. I used gganimate package by Thomas Lin Pedersen. For making the maps, I also used the data set from fiftystater package. Unfortunately the package is no more available on CRAN because it is not available for the latest versions of R. However, you can download the underlying data set from the developer’s Github page. The code to produce this visualization is as follows. The animation is at the bottom of this post

library(ggthemes) # theme_maps() comes from here

I already cleaned up the data for our use. You can download it from my Dropbox. I am reading it here into the opioid_dt data frame.

opioid_dt <- readRDS('opioid_1999_2017.rds')

Next read fifty_states.rda.


Merge the two files. I am creating a new variable state2 in opioid_dt to store lowercase state names. This is required for matching with fifty_states which has state names in a variable id all in lower case.

opioid_state <- opioid_dt %>% 
  mutate(state2 = tolower(state)) %>% 
  inner_join(fifty_states, by = c("state2" = "id"))

Now we are ready to make the animation. Create a ggplot first.

plot1 <- ggplot(data = opioid_state,
       mapping = aes(x = long, y = lat,
                     group = group,
                     fill = opioid_overdose_death)) +
  geom_polygon(color = "gray90", size = 0.05) +
  coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
  scale_fill_viridis_c(option = "plasma") + 
  labs(fill = NULL, title = 'Year: {round(frame_time, 0)}',
       caption = "Created by: Ashwin Malshe
       Credit: Kieran Healy and Thomas Lin Pedersen") +
  theme_map() +
  theme(legend.position = "bottom", 
        plot.title = element_text(family = "Roboto Condensed",
                                  hjust = 0.5, size = 16),
        plot.caption = element_text(family = "Roboto Condensed",
                                    size = 16)) +
  # These two functions below will create a `gganim` object.
  transition_time(year) + 

Render the animation.

animate(plot1, renderer = ffmpeg_renderer())

Go back up

It is likely that you want to save the animation as a GIF. Run the following line to save it to your local disk:



comments powered by Disqus