2012-04-06 66 views
2

我想從全部vs全部比較中生成熱圖。我有這些數據,已經縮小到0-1。然而,我只以一種方式比較價值,而不是在同一組(總是1)之間進行比較,即我有一半的矩陣並且缺少另一半和對角線。 什麼是將ggplot2用於熱圖的形式的好方法?在ggplot2中擴展用於繪製熱圖的數據框

這是數據的一個例子,我有:

A B value 
T1 T2 0.347 
T1 T3 0.669 
T2 T3 0.214 

我認爲以下是我所需要的ggplot(或者也許我不這樣做,如果ggplot能以某種方式產生的呢?):

A B value 
T1 T2 0.347 
T1 T3 0.669 
T2 T3 0.214 
T2 T1 0.347 
T3 T1 0.669 
T3 T2 0.214 
T1 T1 1 
T2 T2 1 
T3 T3 1 

然後我會跑

sorted<-data[order(data$A, data$B), ] 

ggplot(sorted, aes(A, B)) + 
    geom_tile(aes(fill = value), colour = "white") + 
    scale_fill_gradient(low = "black", high = "red") + 

我已經解決了這一點,但(我認爲是)一個非常糟糕的方式INVO存在循環。從第一個數據框到第二個數據框必須有更好的方法!

乾杯

回答

1

嗯......我能想象一個優雅的內置現有的,但這應該爲你做的伎倆:

# Factors are not your friend here 
options(stringsAsFactors = FALSE) 

# Here's the data you're starting with 
this.half <- data.frame(A = c("T1", "T1", "T2"), 
         B = c("T2", "T3", "T3"), 
         value = c(0.347, 0.669, 0.214)) 


# Make a new data.frame, simply reversing A and B 
that.half <- data.frame(A = this.half$B, 
         B = this.half$A, 
         value = this.half$value) 

# Here's the diagonal 
diagonal <- data.frame(A = unique(c(this.half$A, this.half$B)), 
         B = unique(c(this.half$A, this.half$B)), 
         value = 1) 

# Mash 'em all together 
full <- rbind(this.half, that.half, diagonal) 
+0

謝謝!這比我的版本好多了。 R是關於子集和組合的,看起來...... – ShellfishGene 2012-04-07 07:44:41