-
-
Save EvaMaeRey/3c24c1c6138f319d279ec5ed6ea98949 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, " "), | |
| 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_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) + | |
| geom_point(aes(color = age), size = 2) + | |
| 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