R绘图(2): 离散/分类变量如何画热图/方块图

2023-06-05,,

相信很多人都看到过上面这种方块图,有点像“华夫饼图”的升级版,也有点像“热图”的离散版。我在一些临床多组学的文章里面看到过好几次这种图,用它来展示病人的临床信息非常合适,我自己也用R包或者AI画过类似的图。今天给大家演示一下,如何用ggplot2里面的geom_tile函数画这种图。

先构造一个练习数据集,假设有15个病人,每个病人有年龄、性别、症状、是否有RNA-seq和WES测序等信息。

library(ggplot2)
library(tidyverse)
library(reshape2)
library(RColorBrewer) clinical.df=data.frame(
patient=paste("P",seq(1:15),sep = ""),
age=sample(20:80,15,replace = T),
gander=sample(c("male","female"),15,replace = T),
symptom=sample(c("mild","moderate","severe"),15,replace = T),
RNAseq=sample(c("yes","no"),15,replace = T),
WES=sample(c("yes","no"),15,replace = T)
)

年龄可以看做是连续的,我们进一步分成三个level,最终的数据格式如下:

clinical.df$age=ifelse(clinical.df$age < 40,"level1",
ifelse(clinical.df$age < 60, "level2","level3"))
# head(clinical.df)
# patient age gander symptom RNAseq WES
# 1 P1 level2 female moderate yes yes
# 2 P2 level2 male mild yes yes
# 3 P3 level2 female mild no no
# 4 P4 level1 male severe no yes
# 5 P5 level2 male mild yes no
# 6 P6 level3 female moderate no yes

在使用geom_tile画方块图之前,需要将宽数据转换为长数据,使用到reshape2中的melt函数

clinical.df2=melt(clinical.df,id="patient")
# head(clinical.df2)
# patient variable value
# 1 P1 age level2
# 2 P2 age level2
# 3 P3 age level2
# 4 P4 age level1
# 5 P5 age level2
# 6 P6 age level3

接下来,为了自定义图形横纵轴变量的顺序,可以人为定义因子变量,并指定因子的level。(这种方法在实际画图中,经常用到)

clinical.df2$patient=factor(clinical.df2$patient,levels = paste("P",seq(1:15),sep = ""))
clinical.df2$variable=factor(clinical.df2$variable,levels = c("WES","RNAseq","symptom","gander","age"))

然后是自定义颜色,创建一个命名的字符串向量,表示颜色的字符串都是通过R包RColorBrewer查询的,可以参考我之前的一篇笔记:ColorBrewer配色方案

cols=c(
"level1"="#E5F5E0","level2"="#A1D99B","level3"="#41AB5D",
"male"="#66C2A5","female"="#FC8D62",
"mild"="#377EB8","moderate"="#FFFF33","severe"="#E41A1C",
"yes"="black","no"="lightgrey"
)

最后开始画图

clinical.df2%>%ggplot(aes(x=patient,y=variable))+
geom_tile(aes(fill=value),color="white",size=1)+ #color和size分别指定方块边线的颜色和粗细
scale_x_discrete("",expand = c(0,0))+ #不显示横纵轴的label文本;画板不延长
scale_y_discrete("",expand = c(0,0))+
scale_fill_manual(values = cols)+ #指定自定义的颜色
theme(
axis.text.x.bottom = element_text(size=10),axis.text.y.left = element_text(size = 12), #修改坐标轴文本大小
axis.ticks = element_blank(), #不显示坐标轴刻度
legend.title = element_blank() #不显示图例title
)
ggsave("tmp.pdf",device = "pdf",width = 21,height = 7,units = "cm")

图中右侧的图例并不是我们想要的,这时还需要用AI稍微编辑一下,最后的效果如下:


关于ggplot2的学习,我之前整理了几篇笔记,感兴趣的小伙伴可以点击下面的链接进行阅读

ggplot2回顾(1): 认识ggplot2

ggplot2回顾(2): 图层语法入门

ggplot2回顾(3): 图层语法基础

ggplot2回顾(4): 瓦片图、多边形图

ggplot2回顾(5): 数据分布的展示

ggplot2回顾(6): ColorBrewer配色方案

ggplot2回顾(7): geom_bar()和 geom_histogram()比较

ggplot2回顾(8): 标度

ggplot2回顾(9): 分面

ggplot2回顾(10): 坐标系

ggplot2回顾(11): 主题设置

ggplot2回顾(12): 一页多图

ggplot2回顾(13): 使用plyr包整理数据

ggplot2回顾(14): 绘图函数--以平行坐标图为例

因水平有限,有错误的地方,欢迎批评指正!

R绘图(2): 离散/分类变量如何画热图/方块图的相关教程结束。

《R绘图(2): 离散/分类变量如何画热图/方块图.doc》

下载本文的Word格式文档,以方便收藏与打印。