使用 ggplot2 在 r 中为热图准备数据框

preparing data frame in r for heatmap with ggplot2

目前正在尝试创建一些遗传数据的热图。这些列当前标记为 s1、s2、s3 等,但我还有一个 .txt 文件,其中包含每个样本的正确对应标签。我不确定我是否需要先用基因表达水平修改 csv 文件,或者我是否可以将它们单独传输到我正在尝试准备的最终将被制成热图的数据框。我也不确定数据框的格式到底应该是什么。如果重要的话,我想使用 ggplot2 创建热图。

到目前为止,这是我的代码:

library(ggplot2)
library(dplyr)
library(magrittr) 

nci <- read.csv('/Users/myname/Desktop/ML Extra Credit/nci.data.csv')
nci.label <-scan(url("https://web.stanford.edu/~hastie/ElemStatLearn/datasets/nci.label",what="")
                 
#Select certain columns (specific years)
mat <- matrix(rexp(200, rate=.1), ncol=20)
rownames(mat) <- paste0('gene',1:nrow(mat))
colnames(mat) <- paste0('sample',1:ncol(mat))
mat[1:5,1:5]

它输出一个示例数据框,如下所示:

    sample1   sample2    sample3   sample4   sample5

gene1 32.278434 16.678512  0.4637713  1.016569  3.353944

gene2  8.719729 11.080337  1.5254223  2.392519  3.503191

gene3  2.199697 18.846487 13.6525699 34.963664  2.511097

gene4  5.860673  2.160185  3.5243884  6.785453  3.947606

gene5 16.363688 38.543575  5.6761373 10.142018 22.481752

任何帮助将不胜感激!!

您将希望获得“长”格式的数据框以便于绘图。这就是所谓的 Tidy Data,它构成了准备使用 ggplot2.

绘制数据的基础

这里的总体思路是,您需要一列用于 x 值,一列用于 y 值,一列用于表示用于图块颜色的值。有很多方法可以做到这一点(参见 melt()pivot_longer()...),但我喜欢使用 tidyr::gather()。由于您使用的是行名,而不是基因列,因此我首先将其创建为数据集中的列。

library(dplyr)
library(tidyr)
library(ggplot2)

set.seed(1234)

# create matrix
mat <- matrix(rexp(200, rate=.1), ncol=20)
rownames(mat) <- paste0('gene',1:nrow(mat))
colnames(mat) <- paste0('sample',1:ncol(mat))
mat[1:5,1:5]

# convert to data.frame and gather
mat <- as.data.frame(mat)
mat$gene <- rownames(mat)
mat <- mat %>% gather(key='sample', value='value', -gene)

ggplot 调用非常简单。我们将每一列分配给 xyfill 美学,然后使用 geom_tile() 创建实际的热图。

ggplot(mat, aes(sample, gene)) + geom_tile(aes(fill=value))