Skip to content

Instantly share code, notes, and snippets.

@thoughtfulbloke
Last active April 22, 2026 10:59
Show Gist options
  • Select an option

  • Save thoughtfulbloke/7de1f0c026b1113d8e5e8347b352868a to your computer and use it in GitHub Desktop.

Select an option

Save thoughtfulbloke/7de1f0c026b1113d8e5e8347b352868a to your computer and use it in GitHub Desktop.
Code for converting a saved webpages of NZ States of Emergency to a graph of time in emergency
# https://www.civildefence.govt.nz/emergency-events/previous-emergencies/declared-states-of-emergency
# Declared state of emergency page, save locally as an html page
# in the working directory called em.html
library(rvest)
library(dplyr)
library(lubridate)
library(ggplot2)
source("~/theme.R")
# Read the local HTML file
page <- read_html("em.html")
# Extract the first table on the page
df <- page |>
html_element("table") |>
html_table(fill = TRUE) |>
as.data.frame()
# remove non-climate ones
climated <- df |>
filter(!(`Hazard Type` %in% c("Earthquake", "Pandemic", "-"))) |>
mutate(regions_affected = 1,
regions_affected = ifelse(Region == "National", 7,1),
Start = dmy(`Start Date`),
End = dmy(`End Date`))
to15 <- climated |>
filter(End < ymd("2026-04-15"))
seqemer <- function(x, em = to15){
dates <- seq.Date(from=em$Start[x], to=em$End[x], by = "day")
rep(dates,em$regions_affected[x])
}
emdays <- as.data.frame(table((year(as.Date(unlist(sapply(1:nrow(to15), seqemer))))))) |>
mutate(Yr = as.character(Var1)) |> select(Yr, emer=Freq)
alldays <- seq.Date(from=ymd("2002-01-01"), to=ymd("2026-04-15"), by = "day")
denominated <- as.data.frame(table((year(alldays)))) |>
mutate(Yr = as.character(Var1)) |> select(Yr, YrCount=Freq) |>
left_join(emdays, by = join_by(Yr)) |>
mutate(Yr = as.numeric(Yr),
emer = ifelse(is.na(emer),0,emer),
percent = 100 * emer/(YrCount*16))
ggplot(denominated, aes(x=Yr,y=percent)) +
geom_col(fill=six_cols[2]) + theme_david() +
scale_y_continuous(breaks=c(0,4,8))+
scale_x_continuous(breaks=c(2002,2015,2026),
labels=c("2002","2015","2026\nto Apr 15"))+
labs(title="NZ regions' days in Climate based States of Emergency as % of total days",
subtitle="100*sum(days regions in State of Emergency)/(number of regions[16] * available days
2002-2025 available days is days in year, 2026 is days to Apr 15",
y="Percentage Days in Climate Emergency", x=NULL,
caption=make_footer(" Source: NZ Civil Defence")) +
theme(plot.caption = element_text(hjust=.8),
axis.title.y.left = element_text(colour=six_cols[2], size=7.4),
axis.text.y.left = element_text(colour=six_cols[2]),
axis.line.y.left = element_line(colour=six_cols[2]),
axis.ticks.y.left = element_line(colour=six_cols[2]),
panel.background = element_rect(colour=NA))
ggsave("~/Desktop/ggsky.jpg", width=2016, height=1134, units="px")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment