由于热图的需求实在是太过于旺盛,这一节我们先来展示如何通过ggplot2
绘制热图,各位看官老爷们,细细品味
pacman::p_load(tidyverse,reshape2,aplot,ggtree)
heatmap <- mtcars %>% scale(center = F) %>%
as.data.frame() %>%
mutate(mtxars=row.names(.)) %>% melt() %>%
ggplot(aes(variable,mtxars,fill=value))+
geom_tile()+theme_minimal()+
theme(axis.text.x =element_text(angle =90,hjust =0.5,vjust = 0.5))+
scale_fill_viridis_c()+scale_y_discrete(position="right")+
xlab(NULL) + ylab(NULL)
heatmap
scale
函数对数据进行标准化时会同时进行标准化
与中心化
,设置center = F,则不进行中心化,
标准化后数据类型则变为矩阵与数组
,通过as.data.frame()
将其转化为数据框,mutate
添加行名,reshape2包提供melt
函数将宽表转为长表
library(ggpubr)
library(patchwork)
p1 <- mtcars %>% scale(center = F) %>%
as.data.frame() %>%
mutate(mtxars=row.names(.)) %>%
select(qsec:mtxars) %>% head() %>%
ggtexttable(rows = NULL,theme = ttheme("mBlue"))
p2 <- mtcars %>% scale(center = F) %>%
as.data.frame() %>%
mutate(mtxars=row.names(.)) %>%
select(qsec:mtxars) %>% head() %>% melt() %>% head() %>%
ggtexttable(rows = NULL,theme = ttheme("mBlue"))
p1/p2
group <- colnames(mtcars) %>% as.data.frame() %>%
mutate(group=rep(LETTERS[1:2],times=c(6, 5))) %>%
mutate(p="group") %>%
ggplot(aes(.,y=p,fill=group))+
geom_tile() +
scale_y_discrete(position="right") +
theme_minimal()+xlab(NULL) + ylab(NULL) +
theme(axis.text.x = element_blank())+
labs(fill = "Group")
注:此处的分组信息为随意构建的,实际应用时读入具体分组文件即可
type <- rownames(mtcars) %>% as.data.frame() %>%
mutate(group=rep(c("gene1","gene2","gene3"),
times=c(10,12,10))) %>%
mutate(p="genetype") %>%
ggplot(aes(p,.,fill=group))+
geom_tile() +
scale_y_discrete(position="right") +
theme_minimal()+xlab(NULL) + ylab(NULL) +
theme(axis.text.y = element_blank(),
axis.text.x =element_text(
angle =90,hjust =0.5,vjust = 0.5))+
labs(fill = "Type")
p <- mtcars %>% scale(center = F) %>% as.data.frame()
phr <- hclust(dist(p)) %>%
ggtree(layout="rectangular",branch.length="none")
phc <- hclust(dist(t(p))) %>%
ggtree() + layout_dendrogram()
注:由于热图为标准化后的数据绘制,因此此处也用其绘制行聚类与列聚类树
heatmap %>%
insert_left(type, width=.05) %>%
insert_left(phr, width=.2) %>%
insert_top(group, height=.05) %>%
insert_top(phc, height=.1)