zl程序教程

您现在的位置是:首页 >  Java

当前栏目

ggplot2优雅的绘制组合版热图

2023-02-18 16:35:33 时间

❝最近在进行绘图实战颇有感触,今天来介绍一下如何使用「ggplot2绘制组合热图」,有时我们如果只想对部分数据进行热图形式的展示可以用到这种类型的图表;绘图过程倒也简单主要是选择好合适的展示场所

library(tidyverse)
library(ggh4x)
library(patchwork)

定义主题

theme_niwot <- function(){
  theme_test()+
    theme(axis.text.y=element_text(color="black",size =8.5),
          axis.ticks= element_blank(),
          strip.background = element_blank(),
          strip.text = element_blank(),
          panel.spacing.y = unit(0,"cm"),
          plot.background = element_blank(),
          panel.border = element_rect(fill=NA,color="white",size=1),
          plot.margin = margin(0,0.2,0,0.2,"cm")
    )
}

加载数据

data <- read_tsv("data.xls")

数据清洗

df <- data %>% pivot_longer(-sample) %>% 
  left_join(.,read_tsv("group.xls"),by="name") %>% 
  arrange(sample) %>% 
  mutate(sample=as.character(sample))

#定义因子
df$sample <- factor(df$sample,levels = df$sample %>% unique())

绘制文本热图

p1 <- df %>%
  ggplot(.,aes(sample,name))+
  geom_tile(color="grey60",fill="white",size=0.2)+
  geom_text(aes(label=value),size=3,color="black",hjust=0.5,vjust=0.5)+
  labs(x = NULL,y = NULL,color=NULL,fill=NULL)+
  theme_niwot()

绘制组合热图

❝此处将数据数据拆分成两份进行图形绘制,本想借助「ggh4x」 的分面功能,但是此份数据不太适合,关于ggh4x后面再做介绍 ❞

p2 <- df %>% filter(group=="A") %>% 
  ggplot(aes(sample,name,fill=value,color=value))+
  geom_tile(color="grey60",fill="white",size=0.2)+
  geom_point(aes(size=value),shape=22)+
  facet_grid2(group~.,scale="free_y",switch = "y")+
  labs(x = NULL,y = NULL,color=NULL,fill=NULL)+
  scale_color_gradientn(colours = rev(RColorBrewer::brewer.pal(11,"RdBu")))+
  scale_fill_gradientn(colours = rev(RColorBrewer::brewer.pal(11,"RdBu")))+
  theme_niwot()+
  theme(legend.position = "bottom")+
  scale_size(guide=NULL)+
  guides(color=guide_colorbar(direction="horizontal",reverse = F,
                              barwidth = unit(17, "cm"),
                              barheight = unit(.5,"cm"))) 
p3 <- df %>% filter(group=="B") %>% 
  ggplot(aes(sample,name,fill=value,color=value))+
  geom_tile(color="grey60",fill="white",size=0.2)+
  geom_text(aes(label=value),size=2.8,color="black",hjust=0.5,vjust=0.5)+
  facet_grid2(group~.,scale="free_y",switch = "y")+
  labs(x = NULL,y = NULL,color=NULL,fill=NULL)+
  scale_color_gradientn(colours = rev(RColorBrewer::brewer.pal(11,"RdBu")))+
  scale_fill_gradientn(colours = rev(RColorBrewer::brewer.pal(11,"RdBu")))+
   theme_niwot()+
  theme(axis.text.x=element_blank())+
  scale_size(guide=NULL)

拼图

p3/p2+plot_layout(heights=c(2,1.2))