扩展数据框以在ggplot2中绘制热图

时间:2012-04-06 14:48:59

标签: r ggplot2

我想从全对比比较生成热图。我有数据,已经缩放到0-1。但是,我只有一种方式的比较值,而不是同一组之间的比较(总是1),即我有一半的矩阵,我错过了另一半和对角线。 将它变成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") +

我已经解决了这个问题,但是(我假设的)是一个涉及循环的非常糟糕的方法。必须有一种更好的方法来形成上面的第一个数据框到第二个!

干杯

1 个答案:

答案 0 :(得分: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)
相关问题