簡體   English   中英

從2個數據框列創建熱圖矩陣

[英]Create matrix for heatmap from 2 data frame columns

我有一個包含兩列的數據框:度量1和度量2。下面提供了一個示例。 我想根據數據創建一個熱圖。 為了有效地做到這一點,我需要對每一列中的值進行裝箱。 對於小節1,我希望箱大小為0.1,對於小節2,我希望箱大小為0.2。 我可以使用下面的代碼分配垃圾箱。

因此,我認為下一步的邏輯步驟是根據度量1和度量2的bin分配創建一個計數矩陣,然后繪制熱圖。

我有兩個問題:

1)如何更改我的箱分配的名稱? 當前它們從1開始。我想命名這些bin,以便bin名稱反映該bin中的最大值,而不僅僅是1,2,3等。

2)如何從箱分配創建計數矩陣?

我期待任何建議。 謝謝。

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

我想出了如何制作計數矩陣,並使用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")

這對我來說足夠好了。 我會弄清楚垃圾桶的重命名。 希望這對嘗試做同一件事的其他人有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM