如何使用 ggplot2 或 R 中的其他方式绘制矩阵中带有数字的矩阵?数字是 vcf 文件中的 snp 计数

How to plot a matrix with numbers in the matrix colored using ggplot2 or other ways in R? The numbers are the snp count from vcf file

我有一个这样的矩阵:

Gene      BRCA         THYM         TGHJ
ACC         23          21           7
XTG         12          13           9
CFG         45          4            8

我想以矩阵的形式绘制它,其中数字根据它们的数量着色;例如,最高数字在 "Red" 中着色,然后颜色强度随着数字的减少而逐渐降低,因此在此 45 中着色 "Red" 并且 4 着色为非常浅的颜色。如果我清楚,请告诉我。

我希望使用 ggplot2 绘制此矩阵,但也非常欢迎使用 R 中的其他方法。像这样的矩阵:

试试这个:

library(dplyr)
library(ggplot2)
df <- data.frame( Gene= c("ACC", "XTG", "CFG"), 
                      BRCA= c(23,12,45), 
                      THYM= c(21,13,4), 
                      TGHJ= c(7,9,8))  
mdf <- gather(df, -Gene, key="key", value="count")
ggplot(mdf, aes(x=Gene, y=key, fill=count, label=count))+
      geom_tile()+
      geom_text()+
      scale_fill_gradient(high="red2", low="white")

由于您的数据似乎是生物学数据,我建议使用热图函数,该函数也已在多个出版物中使用。

library(gplots)
heatmap.2(as.matrix(df[-1]),
          scale = "none",
          trace = "none", 
          labRow = as.character(df$Gene),
          cexRow=0.9, cexCol = 0.9, 
          cellnote=as.matrix(df[-1]),
          notecol="black",
          notecex = 2)

也尝试通过例如scale = c("none","row", "column") 或通过 dendrogram = c("both","row","column","none") 进行不同的排序。您可以尝试更改颜色col= colorpanel(10, low = "white", mid = "yellow", high = "red")

您可以使用 pheatmap 包。

library(pheatmap)

示例数据集。

df <- data.frame(Gene= c("ACC", "XTG", "CFG"), 
              BRCA= c(23,12,45), 
              THYM= c(21,13,4), 
              TGHJ= c(7,9,8))  

准备绘图数据。

rownames(df) <- df[,1]
m <- as.matrix(df[,-1])

情节。

pheatmap(m, display_numbers=T, show_colnames=T, cluster_rows=F, cluster_cols=F)