Skip to content

Instantly share code, notes, and snippets.

@colinsheppard
Created March 27, 2020 19:29
Show Gist options
  • Save colinsheppard/6c750828cb01b49059c4f68e76796e3c to your computer and use it in GitHub Desktop.
Save colinsheppard/6c750828cb01b49059c4f68e76796e3c to your computer and use it in GitHub Desktop.
animate U.S. covide cases over time
#install.packages('rlang',repos=c('https://ftp.osuosl.org/pub/cran/'))
#install.packages('tidyverse',repos=c('https://ftp.osuosl.org/pub/cran/'))
#install.packages('magick',repos=c('https://ftp.osuosl.org/pub/cran/'))
#install.packages('gganimate',repos=c('https://ftp.osuosl.org/pub/cran/'))
#install.packages('mapproj',repos=c('https://ftp.osuosl.org/pub/cran/'))
#install.packages('devtools',repos=c('https://ftp.osuosl.org/pub/cran/'))
#install.packages('gifski',repos=c('https://ftp.osuosl.org/pub/cran/'))
#library(devtools)
#install_github("UrbanInstitute/urbnmapr")
library(tidyverse)
library(urbnmapr)
library(gganimate)
library(magick)
cov <- data.table(read.csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv'))
counties <- data.table(urbnmapr::counties)
counties[,fips:=as.numeric(county_fips)]
# seriously? they've mixed NYC with counties, so let's define a new "county" called NYC and add
counties[state_abbv=='NY'&county_name%in%c('New York County','Bronx County','Kings County','Queens County','Richmond County')] -> nyc
nyc[,fips:=99999]
nyc[,piece:=as.numeric(factor(group))]
nyc[,county_name:='NYC']
counties <- rbindlist(list(counties,nyc))
cov[county=='New York City',fips:=99999]
dat <- join.on(cov,counties[!is.na(long)],'fips','fips',allow.cartesian=T)[!is.na(fips) & !is.na(long)]
setkey(dat,date,fips)
cov.map <- dat[,.(long=mean(long,na.rm=T),lat=mean(lat,na.rm=T),cases=cases[1],deaths=deaths[1]),by=c('date','fips')]
cov.map[,t:=to.posix(date)]
p <- ggplot() +
geom_polygon(data = states, mapping = aes(x = long, y = lat, group = group),fill = "white", color = 'lightgrey',size=.2) +
coord_map(projection = 'albers', lat0 = 39, lat1 = 45)+
geom_point(dat=cov.map[t>to.posix('2020-03-02')],aes(x=long,y=lat,size=cases,stroke=0.5,group=fips),alpha=.3,colour='red')+
scale_size_continuous(range=c(0.5,60))+
theme(legend.position = "none")+
labs(title="{frame_time}")+
transition_states(fips,transition_length = 1.5,state_length = 1) +
transition_time(t)+enter_fade() + exit_fade()
anim <- animate(p,nframes=length(u(cov.map[t>to.posix('2020-03-02')]$t))*10, fps=15, renderer =gifski_renderer("/Users/critter/Dropbox/home/covid/covid-sm.gif"),width=900,height=500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment