ggplot2优雅绘制时间序列热图

2024-01-10 15:37:45 浏览数 (2)

加载R包

代码语言:javascript复制
library(tidyverse)
library(MetBrewer)
library(ggtext)
library(cowplot)
library(janitor)

导入数据

代码语言:javascript复制
data = read_csv("data.csv") %>% clean_names()

数据筛选

代码语言:javascript复制
# 筛选2016年及以后的数据,并转换日期格式
data1 = data %>%
  filter(year>=2016) %>%
  mutate(mth = match(months, month.name)) %>%
  mutate(date= zoo::as.yearmon(paste(year, mth), "%Y %m"))

排序

代码语言:javascript复制
lev =data1 %>% filter(date==max(date)) %>%
  select(area,value, date) %>% 
  arrange(value) %>%
  pull(area) 

数据可视化

代码语言:javascript复制
data1 %>%
  ggplot(aes(x=date, y=factor(area, levels=lev), fill=value))  
  geom_tile(height=.7)  
  # 在热图上添加文本
  geom_text(data=data1 %>% filter(date==max(date)), 
            aes(x=date .8, label=scales::percent(value, scale=1, accuracy=.01)), 
            size=3,hjust=1) 
  # 添加注释
  annotate(geom="text", size=3,hjust=.8, x=2024, y=21.8, label="2023")   
  # 设置颜色渐变和标签格式
  scale_fill_gradientn(colors=met.brewer("Derain"),
                       labels=scales::percent_format(scale=1)) 
  # 设置X轴和Y轴
  scale_x_continuous(position="top", breaks=seq(2016,2023,1),
                     expand = expansion(mult = c(0,0.2)))  
  scale_y_discrete(expand = expansion(mult = c(0, 0)))  
  # 设置坐标轴和主题
  coord_cartesian(clip="off")  
  theme_minimal_vgrid(15)  
  theme(panel.grid.major.x=element_line(color="grey70", size=.3),
        legend.position = "top",
        axis.title=element_blank(),
        axis.ticks.y.left = element_blank(),
        legend.title=element_blank(),
        plot.margin=margin(.5,.75,.3,.5,unit="cm"),
        legend.margin=margin(l=26),
        axis.text.x.top = element_text(size=9,face="bold"),
        axis.text.y = element_text(size=10,face="bold"),
        legend.text=element_text(size=10,color="black"),
        axis.line.y = element_blank())  
  # 设置颜色条指南
  guides(fill=guide_colorbar(barwidth = unit(18, "lines"), 
                             barheight = unit(.9, "lines")))

0 人点赞