library(tidyverse)
library(ggsankey)
library(wesanderson)
records <- read_csv('records.txt')
drivers <- read_csv('drivers.txt')
pal <- wes_palette("Zissou1")
theme_set(
theme_minimal() +
theme(
legend.title = element_blank(),
legend.key.size = unit(1, "line"),
axis.title = element_blank(),
plot.background = element_rect(fill = "grey97", color = NA),
plot.margin = margin(10, 10, 10, 10),
plot.title = element_text(face = "bold"),
plot.subtitle = element_text(color = "grey30")
)
)
drivers_top <- drivers %>%
filter(position < 6) %>%
mutate(
player_rec = paste0(player, " - ", total, " records"),
player_rec = fct_reorder(player_rec, -total)
)
df <- records %>%
filter(player %in% drivers_top$player) %>%
make_long(player, track) %>% #使用make_long函数转化为ggsankey所需要的格式,
left_join(drivers_top %>%
distinct(player,position),
by = c("node" = "player")) %>%
mutate(color = if_else(!is.na(next_node), pal[position], "white"))
ggplot(df,aes(x = x, next_x = next_x, node = node,
next_node = next_node, fill = color,label = node)) +
geom_sankey() +
# 设置文本
geom_sankey_text(aes(hjust = if_else(x == "track", 1, 0)),size = 3) +
scale_fill_identity() +
coord_cartesian(expand = FALSE, clip = "off") +
theme(
legend.position = "none",
axis.text = element_blank(),
panel.grid = element_blank(),
plot.title = element_text(hjust = 0.5, size = 23, face = "bold"),
plot.caption = element_text(hjust = 0.5)
)