如何为 table 中的每一列创建热图

How to create a heat Map for each column in a table

我想创建一个热图,显示最高值的颜色可能是浅蓝色,最低值是深蓝色和整个列的不同阴影。这应该是逐列的,而不是完整的 table。

我该怎么做?

示例代码:

library(gtable)
library(grid)
library(gridExtra)

g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
    grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
    t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
    grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
    t = 1, l = 1, r = ncol(g))
grid.draw(g)

您可以通过定义主题来实现

library(gtable)
library(grid)
library(gridExtra)

iris <- as.matrix(iris[1:4, 1:3])

# a simple function to scale each column to the range [0, 1]
norm <- function(x) {
    apply(x, 2, function(y){(y-min(y))/(max(y)-min(y))})
}

bluecol <- colorRamp(c("#3366EE", "#AABBFF", "#DDDDFF"))(norm(iris))
bluecol <- rgb(bluecol[, 1], bluecol[, 2], bluecol[, 3], max=255)

tt <- ttheme_default(core=list(bg_params=list(fill=bluecol)))

g <- tableGrob(iris, theme=tt)
g <- gtable_add_grob(g,
    grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
    t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
    grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
    t = 1, l = 1, r = ncol(g))
grid.draw(g)

grid.table 中有一个鲜为人知的功能,可让您使用任意 grob 覆盖负责为每个单元格创建 textGrob 的函数。因此理论上可以处理每个单元格的值并将其变成彩色矩形,例如,或迷你图等。虽然它有点笨拙,而且非常慢。这是一个整体table的通用比例的插图,但它应该很容易适应这个问题(但我认为grid.table不是正确的开始方法)。

d <- as.matrix(iris[1:4, 1:3])

colourise <- function(d, colours = blues9){
  new <- scales::colour_ramp(colours)(scales::rescale(d))
  dim(new) <- dim(d)
  new
}

library(grid)
library(gridExtra)

my_fun <- function(label, ...){

  g <- rectGrob( gp=gpar(fill=label,col="white",lwd=2))
  grobTree(g,cl="cell") # wrapper to give a size
}

# cells need an absolute size
widthDetails.cell <- function(x)
  unit(1,"lines")
heightDetails.cell <- function(x)
  unit(1,"lines")


tt <- ttheme_minimal(12, core=list(fg_fun = my_fun), 
                     colhead=list(fg_params=list(fontface="bold")))

grid.newpage()
grid.arrange(tableGrob(colourise(d), cols=colnames(d), theme = tt), tableGrob(d,rows=NULL))