如何为表中的每列创建热图

时间:2017-05-18 17:28:18

标签: r r-grid gtable

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

我将如何做到这一点?

示例代码:

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)

2 个答案:

答案 0 :(得分:1)

您可以通过定义主题

来实现
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)

enter image description here

答案 1 :(得分:0)

grid.table中有一个鲜为人知的特性,它允许你用任意的grob覆盖负责为每个单元格创建textGrob的函数。因此理论上可以处理每个单元格的值并将其转换为彩色矩形,例如,或者火花线等。虽然有点尴尬,但速度很慢。下面是整个表格的常见比例说明,但应该很容易适应问题(但我不认为grid.table是开始的正确方法)。

enter image description here

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))