使用R中的pheatmap定义特定值着色

时间:2015-09-13 00:48:59

标签: r matrix colors pheatmap

让我们说:

m1<-matrix(rnorm(1000),ncol=100)

并定义颜色:

cols = colorRampPalette(c("white", "red"))(30)

我正在制作一个没有使用pheatmap函数进行聚类的热图:

pheatmap(dist(t(m1)), cluster_rows = F, cluster_cols = F, show_rownames = TRUE, 
color = cols, main = 'Heatmap')

问题是,如何定义颜色以获得相同的热图,但只能使用特定值的像素(例如小于0.1)。

我试图设置

cols = ifelse(dist(t(m1))<0.1,'red','black')

但没有用。

2 个答案:

答案 0 :(得分:6)

对于简单的二进制颜色方案,您可以使用breaks参数:

library(pheatmap)

set.seed(1)
m1<-matrix(c(rnorm(1000)), ncol=100)

pheatmap(dist(t(m1)),
         cluster_rows = F,
         cluster_cols = F,
         show_rownames = TRUE, 
         color = c("red", "black"),
         breaks = c(0, 3, 9),  # distances 0 to 3 are red, 3 to 9 black
         main = 'Heatmap')

看起来像这样:

enter image description here

如果您喜欢颜色渐变,可以按照以下步骤进行操作:

m <- matrix(c(rnorm(1000)), ncol=100)
distmat <- dist(t(m))

# Returns a vector of 'num.colors.in.palette'+1 colors. The first 'cutoff.fraction'
# fraction of the palette interpolates between colors[1] and colors[2], the remainder
# between colors[3] and colors[4]. 'num.colors.in.palette' must be sufficiently large
# to get smooth color gradients.
makeColorRampPalette <- function(colors, cutoff.fraction, num.colors.in.palette)
{
  stopifnot(length(colors) == 4)
  ramp1 <- colorRampPalette(colors[1:2])(num.colors.in.palette * cutoff.fraction)
  ramp2 <- colorRampPalette(colors[3:4])(num.colors.in.palette * (1 - cutoff.fraction))
  return(c(ramp1, ramp2))
}

cutoff.distance <- 3  
cols <- makeColorRampPalette(c("white", "red",    # distances 0 to 3 colored from white to red
                               "green", "black"), # distances 3 to max(distmat) colored from green to black
                             cutoff.distance / max(distmat),
                             100)

pheatmap(distmat,
         cluster_rows = F,
         cluster_cols = F,
         show_rownames = TRUE, 
         color = cols,
         main = 'Heatmap')

然后看起来像这样:

enter image description here

答案 1 :(得分:2)

不是你要求的,但这里有一个可以帮助别人的ggplot解决方案。

set.seed(1)         # for reproducible example
m1 <- matrix(rnorm(1000),ncol=100)
d  <- dist(t(m1))

library(ggplot2)
library(reshape2)   # for melt(...)
gg.df <- melt(as.matrix(d), varnames=c("row","col"))

# fill is red for value < 3; black for value >= 3
ggplot(gg.df, aes(x=factor(col), y=factor(row)))+ 
  geom_tile(aes(fill=ifelse(value<3, "below", "above")), color=NA)+
  scale_fill_manual("Threshold",values=c(below="#FF0000", above="#000000"))+
  coord_fixed()

# fill is black for value > 3; gradient white to red for value <= 3
ggplot(gg.df, aes(x=factor(col), y=factor(row)))+ 
  geom_tile(aes(fill=value), color=NA)+
  scale_fill_gradient(low="#FFFFFF", high="#FF0000", limits=c(0,3), na.value="black")+
  coord_fixed()