gpt4 book ai didi

r - 在 R 中使用 pheatmap 定义特定值着色

转载 作者:行者123 更新时间:2023-12-02 08:35:39 24 4
gpt4 key购买 nike

比方说:

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

但没有成功。

最佳答案

对于简单的二元配色方案,您可以使用 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

关于r - 在 R 中使用 pheatmap 定义特定值着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32545256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com