欢迎关注R语言数据分析指南
❝本节来介绍如何绘制ggplot2版circlize图,下面来看具体案例
❞
加载R包
library(tidyverse)
library(countrycode)
library(circlize)
library(cowplot)
library(grid)
library(ggplotify)
加载数据
df <- readr::read_csv('erasmus.csv')
选择标签
top_countries <- c("Germany","Italy","Spain","Poland","United Kingdom","Romania","Belgium","France","Netherlands (the)","Austria" ,"Luxembourg","Lithuania","Czechia")
数据清洗
data<-df%>%
mutate(
to= countrycode(receiving_country_code, origin="iso2c", destination="iso.name.en"),
from= countrycode(sending_country_code , origin="iso2c", destination="iso.name.en"))%>%
mutate(
to = replace(to, receiving_country_code=="UK","United Kingdom"),
from = replace(from, sending_country_code=="UK","United Kingdom"),
to = replace(to, receiving_country_code=="EL","Greece"),
from = replace(from, sending_country_code=="EL","Greece")
)%>%
group_by(from, to)%>%
summarise(value=sum(participants))%>%
arrange(-value)
# A tibble: 933 × 3
# Groups: from [54]
from to value
<chr> <chr> <dbl>
1 Germany Germany 33076
2 Poland Poland 30036
3 United Kingdom United Kingdom 18964
4 Spain Spain 16572
5 France France 15249
6 Hungary Hungary 15219
7 Czechia Czechia 13205
8 Romania Romania 13064
9 Turkey Turkey 11805
10 Slovakia Slovakia 11014
# … with 923 more rows
提取部分数据
chord_data<-data%>%
filter(from!=to)%>%
filter(from %in% top_countries & to %in% top_countries)%>%
arrange(-value)
chord_data[chord_data=="Netherlands (the)"]<-"Netherlands"
定义颜色
pal<-c("#002765","#0061fd","#1cc6ff","#00b661","#5bf34d","#ffdd00","#ff7d00","#da2818","#ff006d","#8f00ff","#453435","black","grey80")
绘制circlize图
chordDiagram(chord_data, grid.col = pal)
转化为gg格式
p<- recordPlot()
as.ggplot(ggdraw(p))+
theme(text=element_text(family="Arial"),
plot.margin=margin(t=20))
数据获取
❝通过「ggplotify」将其转化为「ggplot」格式后,可以使用相对应的语法很是方便;喜欢的小伙伴欢迎转发此文档附上一句话到朋友圈「30分钟后台截图给我」,即可获取对应的数据及代码,如未及时回复可添加我的微信
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流

「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐

