繁体   English   中英

具有连续彩虹色的热图

[英]Heatmap with continuous rainbow colours

首先,我必须说我在stackoverflow和其他地方读了很多关于heatmap和ggplot2的线程。 但我的问题还没有解决。

我有以下数据集:

   Var1   Var2 value
1 -197.5 -197.5     0
2 -192.5 -197.5     0
3 -187.5 -197.5     0
4 -182.5 -197.5     0
5 -177.5 -197.5     0
6 -172.5 -197.5     0
.....

值应该是颜色,右侧的图例会很好。

library(ggplot2)
ggheatmap <- ggplot(data = dat.plot, aes(x=Var1, y=Var2, fill=value)) + 
  geom_raster()+
  scale_fill_gradientn(colours=rainbow(100))+
  theme(axis.text.x = element_text(angle = 0))+ 
  coord_fixed()
print(ggheatmap)

结果是:

绘图/热图

我希望有一个“正常”的彩虹刻度,从红色=高于橙色,黄色,绿色,浅蓝色,深蓝色=低而不提供固定的离散颜色,就像人们可以做到的那样,例如使用scale_fill_gradient2。 我想知道为什么“彩虹”从红色开始=高端以及其他一些红色......

另一个问题:我如何添加一些东西来“平滑”热图,以便人们不会到处看到“边缘”?

简短的回答:功能rainbow()当你通过去坚果 100为你问100不同的颜色。

你应该怎么做:将n传递给rainbow()以获得你想要的颜色数量。 如果你想从蓝色变为红色,那么你还必须用函数rev()包装它。

library(egg)
library(ggplot2)
library(reshape2)

# Heatmap number of rows/columns
Nvalue <- 1e2
# n for colors passed to function rainbow
nColor <- c(1:10, seq(20, 100, 20))
# dummy data
df <- melt(matrix(rnorm(N^2), N))

plotList <- list()
for(i in seq_along(nColor)) {
    plotList[[i]] <- ggplot(df, aes(Var1, Var2, fill = value)) + 
        geom_raster() +
        scale_fill_gradientn(colours = rev(rainbow(nColor[i]))) +
        labs(title = paste0("rainbow(", nColor[i], ")"),
             x = NULL,
             y = NULL,
             fill = NULL) +
        theme_void()
}

ggarrange(plots = plotList)

在此输入图像描述

编辑:

在OP指定颜色后,他想要传递十六进制矢量应该工作:

hex <- c("#FF0000", "#FFA500", "#FFFF00", "#008000", "#9999ff", "#000066")
ggplot(df, aes(Var1, Var2, fill = value)) + 
        geom_raster() +
        scale_fill_gradientn(colours = rev(hex)) +
        labs(x = NULL,
             y = NULL,
             fill = NULL) +
        theme_void()

在此输入图像描述

在“旧忠实”数据中最好地说明了用复杂色标内插颜色的问题。

如果使用用户定义的“彩虹”色标,插值将不会那么好(即使结果看起来仍然很好)。

没有插值

library(ggplot2)
cols <- rev(rainbow(7)[-7])

ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density), interpolate = FALSE) +
  scale_fill_gradientn(colours = cols)

没有插值

用插值

ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density), interpolate = TRUE) +
  scale_fill_gradientn(colours = cols)

用插值

使用插值和不太复杂的调色板

ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density), interpolate = TRUE) +
  scale_fill_gradientn(colours = c("steelblue", "tomato"))

两个调色板

ggheatmap <- ggplot(data = dat.plot, aes(x=Var1, y=Var2, fill=value)) + 
  geom_raster(interpolate=TRUE)+
  scale_fill_gradientn(colors=rev(c("darkred", "red", "orange", "yellow",    "green", "lightgreen", "lightblue", "darkblue")))+
  theme(axis.text.x = element_text(angle = 0))+ 
  coord_fixed()
print(ggheatmap)

现在看起来很模糊。 但是好的如果你认为它不能做得更好,我就让它原样。 非常感谢你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM