【问题标题】:Create matrix for heatmap from 2 data frame columns从 2 个数据框列创建热图矩阵
【发布时间】:2014-05-27 12:53:18
【问题描述】:

我有一个包含 2 列的数据框:度量 1 和度量 2。我在下面提供了一个示例。我想从数据中创建一个热图。为了有效地做到这一点,我需要对每列中的值进行分类。对于度量 1,我想要 0.1 的 bin 大小,对于度量 2,我想要 0.2 的 bin 大小。我可以使用下面的代码分配垃圾箱。

据此,我认为下一个合乎逻辑的步骤是根据度量 1 和度量 2 的 bin 分配创建一个计数矩阵,然后绘制热图。

我有两个问题:

1) 如何更改我的垃圾箱分配的名称?目前它们从 1 开始。我想命名这些 bin,以便 bin 名称反映该 bin 中的最大值,而不仅仅是 1、2、3 等。

2) 如何从 bin 分配中创建计数矩阵?

我期待任何建议。谢谢。

    #test dataframe
    hsim = matrix(rnorm(100 * 2, 1, 0.25), nrow=100, ncol=2, byrow=FALSE)
    colnames(hsim) = c("measure1", "measure2")
    hsim = as.data.frame(hsim)

    #bin measure 1 by bin size of 0.1
    FindBin.m1 = function(data){
      bin = seq(from=0.52, to=1.6, by=.1) #Specify the bins
      data$bin_index = findInterval(data$measure1, bin) #Determine which bin the value is in 
      }

    hsim$m1bin = FindBin.m1(hsim)

    #bin measure 2 by bin size of 0.2
    FindBin.m2 = function(data){
      bin = seq(from=0.4, to=1.6, by=.2) #Specify the bins
      data$bin_index = findInterval(data$measure2, bin) #Determine which bin the value is in 
      }

    hsim$m2bin = FindBin.m2(hsim)

    #how would I rename the bin indicies in the functions so that they reflect the max number in the bin?
    #for example, in FindBin.m1, bin index 1 represents 0.52 to 0.62. I want to name the bin 0.62 not 1

    #create a count matrix from the m1 and m2 bin assignments that can be used to plot a heatmap

    #plot heatmap
    heatmap(matrix.to.plot)

【问题讨论】:

    标签: r matrix heatmap bin


    【解决方案1】:

    我想出了如何制作计数矩阵,并使用 ggplot 将其作为数据框进行了尝试。这是我最终添加到上面的代码。

        hsim2 = hsim[,3:4]
        hsim2.t = table(hsim2)
        #basic heatmap using the count matrix
        heatmap(hsim2.t)
    
        hsim2.t2 = as.data.frame(hsim2.t)
        #make a nicer looking heatmap
        ggplot(hsim2.t2, aes(m1bin, m2bin)) + geom_tile(aes(fill = Freq)) + scale_fill_gradient(low = "white",high = "steelblue")
    

    这对我来说已经足够好了。我会弄清楚垃圾箱的重命名。希望这可以帮助其他尝试做同样事情的人。

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 2020-09-11
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多