这个案例来源于:Holy ifelse() statements Batman! 不过作者的代码比较老了,我重写了爬取代码,另外作者处理数据过程有点错误,所以我最后画的图和作者的不一样。
首先需要从A Visual Guide to All 37 Villains in the Batman TV Series爬取每个反派出现的季数和集数的数据,为了方便大家复现这个案例,我已经把这个网页下载保存成了 visual-guide-all-37-villains-batman-tv-series.html
文件。
library(tidyverse)
library(rvest)
# 为了方便大家之后的运行,我把这个网页下载下来了:
# download.file('http://mentalfloss.com/article/60213/visual-guide-all-37-villains-batman-tv-series',
# 'visual-guide-all-37-villains-batman-tv-series.html')
# 反派的名字
read_html('visual-guide-all-37-villains-batman-tv-series.html') %>%
html_nodes(css = "#article-1 > div > div.article-body-section.top-leaderboard-limit > div.article-body-content-container > div.article-body-content > div.article-body > h4") %>%
html_text() %>%
as_tibble() -> namedf
read_html('visual-guide-all-37-villains-batman-tv-series.html') %>%
html_nodes(css = "strong i") %>%
html_text() %>%
as_tibble() -> seasondf
bind_cols(namedf, seasondf) %>%
set_names(c("name", "v2")) %>%
mutate(v2 = str_remove_all(v2, "EPISODES "),
v2 = str_remove_all(v2, "EPISODE ")) %>%
separate_rows("v2", sep = "SEASON ") %>%
dplyr::filter(v2 != "") %>%
separate(v2, into = c("season", "episode"),
sep = " \\(") %>%
mutate(episode = str_remove_all(episode, ","),
episode = str_remove_all(episode, "\\)")) %>%
tidytext::unnest_tokens(episode, episode,
token = stringr::str_split,
pattern = " ") %>%
dplyr::filter(episode != "") %>%
mutate(name = str_remove_all(name, "\\d+\\. ")) %>%
type_convert() %>%
mutate(name = str_replace_all(name, " \\(", "\n\\(")) %>%
mutate(to = str_c(season, episode)) %>%
rename(from = name) %>%
select(-episode) %>%
select(to, from, season) -> df
df
然后可以绘制一副网络图展示各个反派出现的集数:
library(ggraph)
library(igraph)
graph <- graph_from_data_frame(as.data.frame(df))
V(graph)$degree <- degree(graph)
n.names <- unique(df$to)
# Fruchterman-Reingold 布局
ggraph(graph, layout = 'fr') +
geom_edge_link(aes(
colour = factor(season)
)) +
geom_node_point(aes(
size = ifelse(V(graph)$name %in% n.names, 1, degree)),
colour = ifelse(V(graph)$name %in% n.names, '#363636', '#ffffff'),
show.legend = F) +
geom_node_text(aes(
label = name),
color = ifelse(V(graph)$name %in% n.names, 'grey', 'white'),
size = ifelse(V(graph)$name %in% n.names, 1.75, 2.5),
repel = T,
check_overlap = T) +
scale_edge_color_brewer('Season',
palette = 'Dark2') +
theme_graph(background = 'grey20',
text_colour = 'white',
base_family = cnfont,
base_size = 10,
subtitle_size = 10,
title_size = 22) +
theme(legend.position = 'bottom') +
labs(
title = '蝙蝠侠中的反派',
subtitle = '节点表示蝙蝠侠电视剧的1——3季中的37个反派,尾端的数字表示出现的季和集数。',
caption = '数据来源: A Visual Guide to All 37 Villains in the Batman TV Series | Mental Floss\n<http://mentalfloss.com/article/60213/visual-guide-all-37-villains-batman-tv-series>')
这样就绘制出了这幅炫酷的网络图。
网友评论