其他
ggplot2优雅的绘制镶嵌条形图
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2」来绘制镶嵌条形图,下面通过一个小例子来展示
❞
❝近期系统整理了一下公众号所写过的一下经典文档,如果需要获取之前绘图文档数据的朋友欢迎加入小编的VIP交流群,「99元即可获取上百篇文档」的代码,目前包含文档「160余篇」公众号右下角添加微信咨询即可
❞
加载R包
library(tidyverse)
library(camcorder)
library(ggtext)
导入数据
incl_gen_2019 <- read_tsv("incl_gen_2019.xls") %>%
mutate(OECD = rowMeans(select(., 3:last_col()))) %>%
rename(provisions = 1) %>%
add_row(provisions = "All provisions", !!! colMeans(.[-1], na.rm = TRUE)) %>%
pivot_longer(2:last_col(), names_to = "country") %>%
mutate(year = 2019, .before = 1)
incl_gen_1999 <- read_tsv("data1990.xls") %>%
mutate(OECD = rowMeans(select(., 3:last_col()), na.rm = TRUE)) %>%
janitor::remove_empty("cols") %>%
select(1, OECD, everything()) %>%
rename(provisions = 1) %>%
add_row(provisions="All provisions",!!!colMeans(.[-1],na.rm = TRUE)) %>%
pivot_longer(2:last_col(), names_to = "country") %>%
mutate(year = 1999, .before = 1)
数据清洗
all_2019 <- incl_gen_2019 %>% filter(startsWith(provisions, "All")) %>%
mutate(country = fct_reorder(country, value))
all_1999 <- incl_gen_1999 %>% filter(startsWith(provisions, "All"))
数据可视化
ggplot() +
geom_col(data = all_2019,
geom_col(data = all_1999, aes(value, country,
fill = if_else(country != "OECD", "#BC83FD","#FCB651")), width = 0.3) +
scale_x_continuous(sec.axis =sec_axis(~./2), # 添加双轴
breaks = seq(0,1,0.2),expand=c(0,0),
limits = c(0,1),labels = scales::label_percent(scale = 100)) +
scale_fill_identity() +
coord_flip()+ # 坐标翻转
theme_minimal() +
theme(
plot.background = element_rect(fill = "grey99", color = NA),
axis.title = element_blank(),
axis.title.x = element_blank(),
axis.line = element_line(color = "#3D4852",size=1),
axis.ticks = element_line(color = "#3D4852",size=1),
panel.grid.major.y = element_line(color = "#DAE1E7"),
panel.grid.major.x = element_blank(),
plot.margin = unit(rep(0.2,4),"cm"),
axis.title.y=element_blank(),
axis.text.y = element_text(margin = margin(r=2),color="black"),
axis.text.x = element_text(margin = margin(t=2,b=10),angle = 90,vjust=0.5,size=12,
hjust=1,color="black"),
legend.position = "non")
❝本节介绍到此结束,需要获取小编之前绘图文档数据及代码的欢迎加入小编的
❞2022年VIP交流群,付费99元
,群内会同步上传公众号文档代码;目前已上传2021-2022约160篇文档代码
;添加小编微信时,请备注单位-方向-姓名以及来意以便高效处理
免费交流群
欢迎大家扫描下方二维码加入「QQ交流群」,与全国各地上千位小伙伴交流