Skip to content

Instantly share code, notes, and snippets.

@USMortality
Last active October 25, 2024 00:11
Show Gist options
  • Save USMortality/7067b000c2275505910c8dc8c959b36d to your computer and use it in GitHub Desktop.
Save USMortality/7067b000c2275505910c8dc8c959b36d to your computer and use it in GitHub Desktop.
Hurricanes [USA]
library(rvest)
library(dplyr)
library(ggplot2)
library(tidyr)
library(scales)
sf <- 2
width <- 600 * sf
height <- 335 * sf
options(vsc.dev.args = list(width = width, height = height, res = 72 * sf))
url <- "https://www.nhc.noaa.gov/pastdec.shtml"
webpage <- read_html(url)
tables <- html_table(webpage, fill = TRUE)
df <- tables[[1]] |>
select(1, 7, 8) |>
setNames(c("decade", "hurricanes", "major_hurricanes")) |>
slice(4:(n() - 3)) |>
mutate(across(c(hurricanes, major_hurricanes), as.integer)) |>
mutate(decade_midpoint = as.numeric(sub("-.*", "", decade)) + 5)
chart <- df |>
ggplot(aes(x = decade_midpoint, y = hurricanes)) +
geom_point(stat = "identity") +
geom_smooth(data = df |> filter(decade != "2021-2023")) +
scale_x_continuous(breaks = df$decade_midpoint, labels = df$decade) +
scale_y_continuous(breaks = scales::pretty_breaks(0)) +
labs(
title = "U.S. Hurricanes Over the Years",
subtitle = "Source: https://www.nhc.noaa.gov/pastdec.shtml",
x = "Decade", y = "Hurricanes"
) +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggplot2::ggsave(
filename = "chart1.png", plot = chart, width = width, height = height,
units = "px", dpi = 72 * sf, device = grDevices::png, type = c("cairo")
)
# Plot using the numeric midpoint for geom_smooth, but keeping the original decade labels
chart <- df |> ggplot(aes(x = decade_midpoint, y = major_hurricanes)) +
geom_point(stat = "identity") +
geom_smooth(data = df |> filter(decade != "2021-2023")) +
scale_x_continuous(breaks = df$decade_midpoint, labels = df$decade) +
scale_y_continuous(breaks = scales::pretty_breaks(0)) +
labs(
title = "Major U.S. Hurricanes (3+) Over the Years",
subtitle = "Source: https://www.nhc.noaa.gov/pastdec.shtml",
x = "Decade", y = "Major Hurricanes"
) +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggplot2::ggsave(
filename = "chart2.png", plot = chart, width = width, height = height,
units = "px", dpi = 72 * sf, device = grDevices::png, type = c("cairo")
)
@USMortality
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment