Created
February 11, 2024 13:41
-
-
Save charliejhadley/b83a4978fe5048aaeb13c934bf9995e1 to your computer and use it in GitHub Desktop.
starwars-graph.R
This file contains 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(tidyverse) | |
library(ggraph) | |
library(tidygraph) | |
nodes_characters <- starwars %>% | |
mutate(character_id = row_number(), .before = 0) %>% | |
mutate(across(where(is.list), ~lengths(.x), .names = "n_{.col}")) | |
edges_reoccuring_co_stars <- nodes_characters %>% | |
filter(n_films > 1) %>% | |
select(character_id, films) %>% | |
unnest(films) %>% | |
left_join(., | |
., | |
by = "films", | |
relationship = "many-to-many") %>% | |
rename(from = character_id.x, | |
to = character_id.y) %>% | |
distinct() %>% | |
filter(from != to) | |
vec_reoccuring_costar_ids <- unique(c(edges_reoccuring_co_stars$from, edges_reoccuring_co_stars$to)) | |
edges_flew_together <- nodes_characters %>% | |
filter(character_id %in% vec_reoccuring_costar_ids) %>% | |
select(character_id, starships) %>% | |
unnest(starships) %>% | |
left_join(., | |
., | |
by = "starships", | |
relationship = "many-to-many") %>% | |
rename(from = character_id.x, | |
to = character_id.y) %>% | |
distinct() %>% | |
filter(from != to) | |
tbl_graph(nodes_characters, | |
edges_flew_together) %>% | |
morph(to_components) %>% | |
mutate(graph_size = graph_size()) %>% | |
unmorph() %>% | |
filter(graph_size > 0) %>% | |
ggraph() + | |
geom_node_point() + | |
geom_edge_link() + | |
geom_node_label(aes(label = name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment