Skip to content

Instantly share code, notes, and snippets.

@acoppock
Created November 25, 2018 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save acoppock/81a80692ed14144800be8ec05529aa74 to your computer and use it in GitHub Desktop.
Save acoppock/81a80692ed14144800be8ec05529aa74 to your computer and use it in GitHub Desktop.
library(rvest)
library(tidyverse)
library(stringr)
library(lubridate)
library(ggrepel)
pres_terms <-
read_html("https://www.presidentsusa.net/presvplist.html") %>%
html_nodes("table") %>%
pluck(1) %>%
html_table(header = TRUE, fill = TRUE) %>%
`[`(-46,c(1:3)) %>%
mutate(President = str_remove(President, "&nbsp"),
President = str_remove(President, "[[:digit:]]+"),
President = str_remove(President, "^\\.+|\\.[^.]*$"),
President = str_trim(President),
term_start = mdy(`Term Began`),
term_end = mdy(`Term Ended`),
term_end = if_else(is.na(term_end), today(), term_end),
pres_num = 1:45) %>%
select(President, term_start, term_end, pres_num)
pres_lives <-
read_html("https://www.presidentsusa.net/birth.html") %>%
html_nodes("table") %>%
pluck(1) %>%
html_table(header = TRUE, fill = TRUE) %>%
mutate(birthdate = mdy(`Birth Date`),
President = str_trim(President),
President = recode(President, "Franklin Roosevelt" = "Franklin D. Roosevelt",
"James A. Garfield" = "James Garfield")) %>%
select(President, birthdate)
presidents <-
full_join(pres_terms, pres_lives) %>%
gather(key, date, term_start, term_end) %>%
mutate(age = as.duration(date - birthdate) / dyears(1),
torch = if_else(key == "term_start", pres_num, as.integer(pres_num + 1)))
label_df <- presidents %>% filter(key == "term_start")
g <-
ggplot(presidents, aes(x = date, y = age, group = President)) +
geom_point(aes(color = age), size = 2) +
geom_line(aes(color = age), size = 1) +
geom_text_repel(data = label_df, aes(label = President), size = 2, nudge_y = -1) +
scale_color_gradient(low = "yellow", high = "black") +
geom_line(aes(group = torch), linetype = "dotted", alpha = 0.3) +
theme_bw() +
theme(axis.title = element_blank(),
legend.position = "none") +
labs(title = "How old is the US President?",
subtitle = "Code and Data: https://gist.github.com/acoppock",
caption = "Source: www.presidentsusa.net")
g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment