ggplot2绘制聚类热图

加载需要的R包:

library(reshape2)

library(ggplot2)

library(ggtree)  #需要在bioconductor下载


读入数据:

gene <- read.csv(file = "clipboard",header = T,sep = "\t",check.names = F,row.names = 1)

gene

gg <- hclust(dist(gene))    #对行聚类

zz <- hclust(dist(t(gene)))    #对列聚类

gene <- gene[,zz$order]      #列,按照聚类结果排序

gene <- gene[gg$order,]     #行,按照聚类结果排序

gene <- cbind(name = row.names(gene),gene)

data <- melt(gene,id.vars = "name")   #宽数据变为长数据

data$num <- rep(c(1:26),6)   #绘图时的纵坐标

data$x <- rep(c(1:6),each = 26)   #绘图时的横坐标


开始绘图:

heatmap <- ggplot(data)+

  geom_tile(aes(x = x,y = num,alpha = 0.7),fill = "white",color = "gray")+

  geom_point(aes(x = x,y = num,size = value,color = value),shape = 18)+

  scale_color_gradient2(low = "green",high = "red",mid = "white",midpoint = 6,name = "FPKM",

                        guide = guide_colourbar(barheight = unit(10,"cm"),title.theme = element_text(size = rel(15))))+

  scale_y_discrete(position = c("right"),limits = factor(c(1:26)),label = gene$name)+

  scale_x_discrete(limits = factor(c(1:6)),label = c(colnames(gene)[2:7]))+

  scale_size_continuous(range = c(4,9),guide = NULL)+

  scale_alpha(guide = NULL)+

  labs(x = NULL)+

  theme(panel.background = element_blank(),

        axis.line.x = element_blank(),

        axis.line.y = element_blank(),

        axis.title.y = element_blank(),

        axis.title.x = element_text(size = rel(2),hjust = 0.5),

        axis.text.x = element_text(size = rel(2),hjust = 0.5),

        axis.text.y = element_text(hjust = 0.5,size = rel(2)),

        axis.ticks.x = element_blank(),

        axis.ticks.y = element_blank(),

        plot.title = element_text(size = rel(1.8)),

        plot.margin = margin(15,9,9,30))


绘制聚类树:

h <- ggtree(gg,layout = "rectangular",branch.length = "none")  # 绘制列聚类树

v <- ggtree(zz)+layout_dendrogram()  # 绘制行聚类树


绘制分组信息:

group <- rep(c("A","B"),each = 3) %>% data.frame(x = c(1:6),y = rep(1,6)) %>%

  ggplot()+

    geom_tile(aes(x,y,fill = .))+

    scale_fill_discrete(label = c("control","treat"))+

    theme(panel.background = element_blank(),

          axis.line = element_blank(),

          axis.title = element_blank(),

          axis.text = element_blank(),

          axis.ticks = element_blank(),

          plot.title = element_blank())


热图和聚类树拼在一起:

heatmap %>% insert_top(group,height = 0.02) %>% insert_top(v,height = 0.1) %>% insert_left(h,width = 0.3)   #使用 aplot包里的函数进行拼图

最终结果:

你可能感兴趣的:(ggplot2绘制聚类热图)