本节来展示使用TidyTuesday 2021第13周的数据集来绘制地图加网络图,使用{widyr}进行成对关联,并使用{ggraph}和{tidygraphs}建立了一个网络,显示欧洲国家在联合国中的投票情况(R> .5)后台回复关键词2021-13获取全文代码与数据
加载R包
library(tidyverse)
library(widyr)
library(tidygraph)
library(ggraph)
library(rnaturalearth)
library(cowplot)
library(extrafont)
读入数据
data <- read.csv("unvotes.csv")
数据清洗
从数据集合中筛选出欧洲的数据
data %>%
left_join(countrycode::codelist %>% select(country_code = iso2c,continent))
euro = unvotes %>% filter(continent == "Europe")
europe = rnaturalearth::ne_countries(continent = "Europe",
scale = "medium") %>% sf::st_as_sf()
pairwise_cor函数计算数据之间的相关性,筛选出correlation> 0.5的数据进行网络图绘制
euro_corrs = euro %>%
mutate(vote = if_else(vote == "yes", TRUE, FALSE)) %>%
pairwise_cor(tbl = ., item = country_code,
feature = rcid, value = vote)
tidytab = euro_corrs %>%
filter(correlation > .5) %>%
as_tbl_graph(directed = F) %>%
mutate(block =
as.factor(group_edge_betweenness(weights =
correlation)))
ggraph绘制网络图
graph = ggraph(tidytab, layout = "kk") +
geom_edge_link(aes(alpha = correlation)) +
geom_node_point(shape = 21,
aes(fill = block), color = "white",
size = 12, stroke = 1.5) +
geom_node_text(aes(label = name), color = "black") +
theme_graph(base_family = "sans") +
theme(legend.position = "none")
欧洲地图
blocks = tidytab %>%
as.data.frame() %>%
tibble() %>%
rename(iso_a2 = name) %>%
left_join(select(unvotes, iso_a2 = country_code)) %>%
distinct()
euro_blocks = europe %>%
left_join(blocks)
map = ggplot(euro_blocks) +
geom_sf(aes(fill = block)) +
scale_x_continuous(limits = c(-40, 85)) +
scale_y_continuous(limits = c(35, 80)) +
theme_void() +
theme(legend.position = "none", panel.border = element_rect(fill = NA))
将地图与网络图组合
ggdraw(graph) +
draw_plot(map, x = .75, y = .75, scale = .4, hjust = .5, vjust = .5)
往期精彩:
配置R与Rstudio
ggplot2中的一些关键概念
tidyverse的基础使用
ggplot2绘制终极版热图
ggtree绘制进化树
初探相关性热图
再探相关性热图
ggplot2绘制相关性热图
初探柱状图
绘制具有显著性的条形图
ggplo2绘制经典条形图
ggplo2绘制双误差线条行图
揭开ggplot2中stat图层的神秘面纱
R中的图片注释神包aplot
ggplot2使用patchwork高质量拼图
ggplot2绘制基础散点图
ggplot2绘制经典散点图-1
ggplot2绘制经典散点图-2
ggplot2绘制云雨图
ggplot2绘制经典云雨图
ggplot2绘制哑铃图
ggplot2绘制经典哑铃图
ggplot2添加git

