Skip to content

Instantly share code, notes, and snippets.

@ofchurches
Last active March 5, 2020 03:34
Show Gist options
  • Save ofchurches/239cd21fc1904739a6ebd2feda0d2aca to your computer and use it in GitHub Desktop.
Save ofchurches/239cd21fc1904739a6ebd2feda0d2aca to your computer and use it in GitHub Desktop.
TidyTuesday_20200303
library(readr)
library(tidyverse)
library(gganimate)
library(tidygraph)
library(igraph)
library(ggraph)
season_goals <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-03/season_goals.csv')
top_8 <- season_goals %>%
select(player, total_goals) %>%
distinct() %>%
top_n(n = 8, wt = total_goals)
hockey_minder <- season_goals %>%
filter(season >= 1969) %>%
mutate(top_player = if_else(player %in% top_8$player, player, "")) %>%
mutate(season_start = as.numeric(str_sub(season, 1, 4))) %>%
ggplot(mapping = aes(x = assists,
y = goals,
colour = team,
size = penalty_min,
label = top_player)) +
theme_bw() +
geom_point() +
geom_text(nudge_y = 12) +
guides(size = FALSE, colour = FALSE) +
labs(title = "Season: {frame_time}", x = "Assists", y = "Goals") +
transition_time(as.integer(season_start)) +
ease_aes('linear')
anim_save("hockey_gif.gif", animate(hockey_minder, fps = 4))
#Load the data
season_goals <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-03/season_goals.csv')
#Prepare the edge list
edge_list <- season_goals %>%
select(player, team) %>%
distinct() %>%
# from here the steps to getting an edge list are from https://stackoverflow.com/questions/34670145/generating-an-edge-list-from-id-and-grouping-vectors
group_by(player) %>%
filter(n()>=2) %>%
group_by(player) %>%
do(data.frame(t(combn(.$team, 2)), stringsAsFactors=FALSE)) %>%
ungroup() %>%
select(-player) %>%
rename(from = X1, to = X2) %>%
# from here the steps to getting the edge weight are from: https://www.jessesadler.com/post/network-analysis-with-r/
group_by(from, to) %>%
summarise(weight = n()) %>%
ungroup()
#Graph it!
# Create graph using tidygraph
graph <- as_tbl_graph(edge_list)
# plot using ggraph
ggraph(graph, layout = 'kk') +
geom_edge_bend(aes(alpha = weight), show.legend = FALSE) +
scale_edge_width(range = c(0.2, 1.5)) +
geom_node_point() +
geom_node_label(aes(label = name), repel = TRUE) +
theme_graph()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment