使用ggplot2每列热图

Rod*_*phe 5 r ggplot2

我正在使用这个R脚本:

tableau <- read.table(
  text = 
    "Net    B   C   D   E.(e)   F.(f)
a   1.88    0.15    0.60    10.00   90.00
b   2.05    0.23    0.51    55.00   80.00
c   2.09    0.29    0.40    58.00   88.00
d   2.07    0.52    0.36    80.00   84.00
e   2.13    0.30    0.27    7.00    90.00",
  header = TRUE)

library(plyr)
library(reshape)
library(ggplot2)
library(scales)
tableau.m <- melt(tableau)
tableau.m <- ddply(tableau.m, .(variable), transform, rescale = rescale(value))

(p <- ggplot(tableau.m, aes(variable, Net)) + 
    geom_tile(aes(fill = rescale), colour = "white") + 
    scale_fill_gradient(low = "white", high = "steelblue"))

base_size <- 9
p + theme_grey(base_size = base_size) + 
  labs(x = "", y = "") + scale_x_discrete(expand = c(0, 0)) + 
  scale_y_discrete(expand = c(0, 0)) + 
  theme(legend.position = "none", axis.ticks = element_blank(), 
        axis.text.x = element_text(size = base_size * 0.8, angle = 0, 
                                   hjust = 0, colour = "grey50"))

tableau.s <- ddply(tableau.m, .(variable), transform, rescale = scale(value))

last_plot() %+% tableau.s
Run Code Online (Sandbox Code Playgroud)

我得到了这个情节:

在此输入图像描述

深蓝色表示较高值,白色表示较低值.

如果可能,我如何更改此代码以便:

  1. 表中的值显示在矩阵图的每个相应单元格中?
  2. 热图的范围不是在整个矩阵上计算的,而是针对每列计算的.因此,对于每个类别:B,C,D,E(e)和F(f),白色表示此列的较低值,而深蓝色表示列的较高值?

谢谢!

eip*_*i10 9

要将value文本标签添加到每个单元格,您可以使用geom_text:

p <- ggplot(tableau.m, aes(variable, Net)) + 
      geom_tile(aes(fill = rescale), colour = "white") + 
      scale_fill_gradient(low = "white", high = "steelblue") +
      geom_text(aes(label=value))

# Add the theme formatting
base_size <- 9
p + theme_grey(base_size = base_size) + 
  labs(x = "", y = "") + scale_x_discrete(expand = c(0, 0)) + 
  scale_y_discrete(expand = c(0, 0)) + 
  theme(legend.position = "none", axis.ticks = element_blank(), 
        axis.text.x = element_text(size = base_size * 0.8, 
                                   angle = 0, hjust = 0, colour = "grey50"))
Run Code Online (Sandbox Code Playgroud)

对于您的第二个问题,您当前的代码已经解决了这个问题.变量rescale分别对每列进行缩放,因为您已执行分组的操作variable.由于rescalefill变量,因此为了设置颜色值,每个列的值从零重新调整为一.您不需要tableau.s ... last.plot...代码.

以下是运行上述代码后情节的样子.请注意,在每列中,最低值为白色,最高值为钢蓝色.(您可能希望将边框颜色从"白色"更改为"gray90",以便相邻的白色方块之间存在边框):

在此输入图像描述