R语言学习指南(5) ggplot2绘制终极版热图

由于热图的需求实在是太过于旺盛,这一节我们继续来通过ggplot2绘制热图,各位看官老爷们,细细品味
喜欢可以关注公众号R语言数据分析指南,先行拜谢了

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_gradientn(colours =rainbow(3))+
  scale_y_discrete(position="right")+
  xlab(NULL) + ylab(NULL)

scale函数对数据进行标准化时会同时进行标准化中心化,设置center = F,
标准化后的数据类型则变为矩阵与数组as.data.frame()将其转化为数据框,mutate添加行名,melt将宽表转为长表

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()

aplot包对5组图进行拼图

heatmap %>%
  insert_left(type, width=.05) %>%
  insert_left(phr, width=.2) %>%
  insert_top(group, height=.05) %>%
  insert_top(phc, height=.1) 

R语言学习指南(5) ggplot2绘制终极版热图_第1张图片

参考: https://mp.weixin.qq.com/s/PioLhBKBP4X8RhJzscrQTQ

你可能感兴趣的:(R语言学习指南(5) ggplot2绘制终极版热图)