Skip to content

Instantly share code, notes, and snippets.

@ivabrunec
Created June 21, 2022 20:28
Show Gist options
  • Save ivabrunec/0164ac7993c0ac65ec1930597ebed4c8 to your computer and use it in GitHub Desktop.
Save ivabrunec/0164ac7993c0ac65ec1930597ebed4c8 to your computer and use it in GitHub Desktop.
## gganimate: gradually reveal underlying stripe image
library(jpeg)
library(grid)
library(ggplot2)
library(scales)
library(gganimate)
library(dplyr)
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
# read in number of natural disasters by year
# https://ourworldindata.org/grapher/number-of-natural-disaster-events
dis_df <- read.csv('number-of-natural-disaster-events.csv')
dis_df <- dis_df %>%
filter(Entity == "Extreme weather" | Entity == 'Drought' |
Entity == 'Extreme temperature' | Entity == 'Flood') %>%
select(Year, Number.of.disasters..EMDAT..2020..) %>%
group_by(Year) %>%
summarise(total_cases = sum(Number.of.disasters..EMDAT..2020..))
# rename to make it cleaner
colnames(dis_df) <- c('year','number')
# add geom_rect parameters so it disappears gradually with each year
for (i in 1:nrow(dis_df)){
dis_df$x_min[i] <- dis_df$year[i]
dis_df$x_max[i] <- max(dis_df$year)
dis_df$y_min[i] <- min(dis_df$number)
dis_df$y_max[i] <- max(dis_df$number)
}
# thanks to this SO question
# https://stackoverflow.com/questions/45777519/use-an-image-as-area-fill-in-an-r-plot
db = readJPEG("stripes_global_1900.jpg")
db = rasterGrob(db, width = unit(1, 'npc'), height = unit(1, 'npc'), interpolate = F)
# specify min and max values for raster
minX = min(dis_df$year+1)
maxX = max(dis_df$year-1)
minY = min(dis_df$number)
maxY = max(dis_df$number-1)
# build animation
anim <- ggplot(data = dis_df, aes(x = year, y = number)) +
annotation_custom(db, xmin = minX, xmax = maxX, ymin = minY, ymax = maxY) +
geom_ribbon(aes(ymin=number, ymax=max(number)), fill="grey96") +
geom_line(color = 'grey94') +
geom_rect(data = dis_df, aes(xmin = x_min, xmax = x_max, ymin = y_min, ymax = y_max),
fill = 'grey96', color = 'grey96')+
theme_minimal(base_size = 14) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.background = element_rect(fill = "grey96", color = NA),
plot.title = element_text(hjust = 0.5, size = 14)) +
scale_x_continuous(breaks=c(1900, 1920, 1940, 1960, 1980, 2000, 2020)) +
labs(x = "",
y = "",
title = "extreme weather events vs. changes in global temperature") +
transition_reveal(year)
# animate & save
animate(anim, fps = 10)
anim_save("stripes.gif", renderer = gifski_renderer(loop = F), ani.res = 400)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment