我目前正在尝试制作自己的图形时间线,就像本页底部的时间线一样。我使用 rvest 包从该链接中刮掉了表格并将其清理干净。
这是我的代码:
library(tidyverse)
library(rvest)
library(ggthemes)
library(lubridate)
URL <- "https://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States"
justices <- URL %>%
read_html %>%
html_node("table.wikitable") %>%
html_table(fill = TRUE) %>%
data.frame()
# Removes weird row at bottom of the table
n <- nrow(justices)
justices <- justices[1:(n - 1), ]
# Separating the information I want
justices <- justices %>%
separate(Justice.2, into = c("name","year"), sep = "\\(") %>%
separate(Tenure, into = c("start", "end"), sep = "\n–") %>%
separate(end, into = c("end", "reason"), sep = "\\(") %>%
select(name, start, end)
# Removes wikipedia tags in start column
justices$start <- gsub('\\[e\\]$|\\[m\\]|\\[j\\]$$','', justices$start)
justices$start <- mdy(justices$start)
# This will replace incumbencies with NA
justices$end <- mdy(justices$end)
# Incumbent judges are still around!
justices[is.na(justices)] <- today()
justices$start = as.Date(justices$start, format = "%m/%d%/Y")
justices$end = as.Date(justices$end, format = "%m/%d%/Y")
justices %>%
ggplot(aes(reorder(x = name, X = start))) +
geom_segment(aes(xend = name,
yend = start,
y = end)) +
coord_flip() +
scale_y_date(date_breaks = "20 years", date_labels = "%Y") +
theme(axis.title = element_blank()) +
theme_fivethirtyeight() +
NULL
这是 ggplot 的输出(我不担心美学,但我知道它看起来很糟糕!):
此图的目标是从开始日期开始按时间顺序排列评委,因此开始日期最早的评委应该在底部,而最近开始的评委应该在顶部。如您所见,有多个实例违反了此规则。
它不是按时间顺序排序,而是简单地将评委按照他们在数据框中出现的顺序列出,这也是维基百科的顺序。因此,另一个线段上方的线段应始终比其下方的线段更靠右
我对重新排序的理解是,它将采用 X = 从 geom_segment 开始并对其进行排序并按该顺序列出名称。
我能找到解决这个问题的唯一帮助是考虑日期,然后以这种方式订购它们,但是我得到了错误
错误:无效输入:date_trans 仅适用于 Date 类的对象。
感谢您的帮助!