其他
ggplot2优雅的绘制环状面积图
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2」绘制环状面积图,下面通过一个小例子来进行展示
❞
安装并加载R包
package.list=c("tidyverse","lubridate","ggstream",
"glue","RColorBrewer","scales","ggtext","geomtextpath")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
加载数据
data <- read_csv("data.csv",
name_repair = function(x) {
str_to_lower(x)
})
数据清洗
long <- data %>%
filter(`-9` != 100) %>%
mutate(good_date = ymd(str_sub(date, 3, 10))) %>%
pivot_longer(cols = c(3:13), names_to = "cat") %>%
select(-c(1:2)) %>%
filter(cat != "-9") %>%
mutate(cat = factor(cat, levels = c(glue("d{0:4}"),
glue("w{0:4}"))))
定义文本坐标
ylabs <- tibble(
x = c("1895-09-01",glue("{seq(from = 1920, to = 2000, by = 20)}-01-01"),
"2022-03-01")) %>% mutate(x = ymd(x),y = 125,yend = -125,
lab = year(x),hjust = c(0,0,0,.5,1,1,1),
vjust = c(-.5, .5,.5, 1, 1, .5, -.5))
数据可视化
long %>%
mutate(value = ifelse(str_detect(cat, "^w"), value * -1, value)) %>%
ggplot(aes(good_date, value, fill = cat)) +
annotate(geom = "rect", xmin = ymd("2015-01-01"), xmax = ymd("2021-01-01"),
ymin = -110, ymax = 100,fill="grey40") +
geom_segment(data = ylabs,
aes(x = x, xend = x, y = y-5, yend = yend),
color = "grey50", inherit.aes = FALSE) +
geom_text(data = ylabs,aes(x = x, y = y, label = lab,
hjust = hjust, vjust = vjust),
color = "black",inherit.aes = FALSE)+
geom_area(position = "identity") +
scale_y_continuous(labels = function(x) glue("{abs(x)}%"),
limits = c(-1000, NA))+
scale_x_date(expand = c(0.02, 0))+
scale_fill_manual(values=c("#67001F","#B2182B","#D6604D","#F4A582","#FDDBC7","#D1E5F0",
"#92C5DE","#4393C3","#2166AC","#053061"))+
coord_curvedpolar(clip = "off")+
theme_void()+
theme(text = element_text(color="black"),
legend.position = c(.5,.5),
legend.title = element_blank(),
legend.key.size = unit(1,"lines")) +
guides(fill = guide_legend(ncol = 2, byrow = TRUE,
label.theme = element_text(color = "black",size = 8)))
数据获取
❝本节内容到此结束,喜欢的小伙伴欢迎转发此文档附上一句话到朋友圈「30分钟后后台截图给我」,即可获取对应的数据及代码,如未及时回复可添加我的微信
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐