Posted on

绘制热图一般可以使用pheatmap包快速绘制,但是使用ggplot2可以实现更多自定义设置,下面代码使用自带mtcars包进行热图绘制,并添加列注释(y轴标签在最外面)

标签显示在最外面的原理很简单,就是热图不显示axis.text.y,而是添加的注释的那个条条添加axis.text.y,如果有多个,只有最外面的显示axis.text.y

library(ggplot2)
library(aplot)
library(tidyr)
##library(ggtree) ##绘制聚类树使用

p <- scale(mtcars) %>% data.frame()
p$mtxars <- rownames(p)
#宽表转长表
p1 <- gather(p, 1:11, key="condition", value='expr')
#绘制热图
pp1 <- ggplot(p1,aes(condition,mtxars)) +
  geom_tile(aes(fill=expr),colour = "white")+ 
  scale_fill_gradientn(values = seq(0,1,0.2),colours =  c('#6699CC','#FFFF99','#CC3333'))+
  theme_minimal()+
  scale_y_discrete(position="right")+
  xlab(NULL) + ylab(NULL)+
  theme(axis.text.y = element_blank())
pp2 <- ggplot(p1,aes(condition,mtxars)) +
  scale_color_gradientn(values = seq(0,1,0.2),colours =  c('#6699CC','#FFFF99','#CC3333'))+
  theme_bw()+
  geom_point(aes(size=expr,color=expr))+
  theme(panel.grid = element_blank(),axis.text.x =element_text(angle =90,hjust =0.5,vjust = 0.5))+
  xlab(NULL) + ylab(NULL)+
  theme(panel.border = element_rect(fill=NA,color="black", size=1, linetype="solid"),
        axis.text.y = element_blank())



Type_A <- rownames(p) %>% as.data.frame() %>%
  mutate(group=rep(c("A","B","C"),
                   times=c(10,10,12))) %>%
  mutate(p="")%>%
  ggplot(aes(p,.,fill=group))+
  geom_tile() + 
  scale_y_discrete(position="right") +
  theme_minimal()+xlab(NULL) + ylab(NULL) +
  theme(axis.text.y = element_blank())+
  labs(fill = "Type_A")
Type_B <- rownames(p) %>% as.data.frame() %>%
  mutate(group=rep(c("D","E","F"),
                   times=c(6,12,14))) %>%
  mutate(p="")%>%
  ggplot(aes(p,.,fill=group))+
  geom_tile() + 
  scale_y_discrete(position="right") +
  theme_minimal()+xlab(NULL) + ylab(NULL)+
  labs(fill = "Type_B")

pp1 %>%
  insert_left(Type_A, width = .05)%>%
  insert_left(Type_B,width=.05)

pp2 %>%
  insert_left(Type_A, width = .05)%>%
  insert_left(Type_B,width=.05)

发表评论

邮箱地址不会被公开。 必填项已用*标注