2012-04-06 46 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