R 中绘图/热图中的颜色

Colours across Plots / Heatmaps in R

我在 R 中创建了一些热图,但在保持图表的色标一致方面遇到了问题。

我发现图表中的颜色是按比例缩放的,有没有办法让图表中的颜色保持一致? IE。所以 0.4 和 0.5 之间的颜色差异总是相同的?

代码示例:

set.seed(123)

d1 = matrix(rnorm(9, mean = 0.2, sd = 0.1), ncol = 3)
d2 = matrix(rnorm(9, mean = 0.8, sd = 0.1), ncol = 3)

mat = list(d1, d2)

for(m in mat)
  heatmap(m, Rowv = NA ,Colv = NA)

您会在示例中注意到,第一个图形中的单元格 (2,3) 与第二个图形中的单元格 (1,3) 相似,尽管相差约 0.8

如果您愿意不使用基本图形,可以使用 ggplot2 来实现:

library(reshape2)
library(ggplot2)

# Set common limits for color scale
limits = range(unlist(mat))

这是两个单独图表的代码。每个图形的最后一行代码确保它们使用相同的 z 限制来设置颜色:

ggplot(melt(mat[[1]]), aes(Var1, Var2, fill=value)) +
  geom_tile() + 
  scale_fill_continuous(limits=limits)

ggplot(melt(mat[[2]]), aes(Var1, Var2, fill=value)) +
  geom_tile() + 
  scale_fill_continuous(limits=limits)

另一种选择是使用分面将两个热图绘制在一个图中,这会自动确保两个图处于相同的色标上:

ggplot(melt(mat), aes(Var1, Var2, fill=value))   +
  geom_tile() + 
  facet_grid(. ~ L1)

我在这里使用了默认颜色,但是对于任何一种方法,您都可以将色阶设置为您想要的任何颜色。例如:

ggplot(melt(mat), aes(Var1, Var2, fill=value))   +
  geom_tile() + 
  facet_grid(. ~ L1) +
  scale_fill_gradient(low="red", high="green")

您可以直接使用 image 函数(heatmap 使用 image),但它需要一些额外的格式来匹配 heatmap 的输出。您可以使用 zlim 设置颜色范围。引用 ?image 页面:

the minimum and maximum z values for which colors should be plotted, defaulting to the range of the finite values of z. Each of the given colors will be used to color an equispaced interval of this range. The midpoints of the intervals cover the range, so that values just outside the range will be plotted.

# define zlim min and max for all the plots
minz = Reduce(min, mat)
maxz = Reduce(max, mat)

for(m in mat) {
  image( m, zlim = c(minz, maxz), col = heat.colors(20))
}

为了更接近 heatmap 生成的格式,您可以重用 heatmap 函数中的一些代码:

for(m in mat) {
  labCol = dim(m)[2]
  labRow = dim(m)[1]
  image(seq_len(labCol), seq_len(labRow), m, zlim = c(minz, maxz),
    col = heat.colors(20), axes = FALSE, xlab = "", ylab = "",
    xlim = 0.5 + c(0, labCol), ylim = 0.5 + c(0, labRow))
  axis(1, 1L:labCol, labels = seq_len(labCol), las = 2, line = -0.5, tick = 0)
  axis(4, 1L:labRow, labels = seq_len(labRow), las = 2, line = -0.5, tick = 0)
}

使用 breaks 参数 image 是另一种选择。在设置颜色断点方面,它比 zlim 更灵活。从帮助页面引用,breaks

a set of finite numeric breakpoints for the colours: must have one more breakpoint than colour and be in increasing order. Unsorted vectors will be sorted, with a warning.