r - 具有连续彩虹颜色的热图

标签 r ggplot2 heatmap

首先我不得不说我在 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)

结果是:

Plot/Heatmap

我想要一个从红色=高到橙色、黄色、绿色、浅蓝色、深蓝色=低的“正常”彩虹等级,而不需要给出固定的离散颜色,例如使用scale_fill_gradient2。 我想知道为什么“彩虹”以红色开头=高端以其他红色结尾......

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

最佳答案

简短回答:当您要求 100 时传递 100 时,函数 rainbow() 发疯> 不同的颜色。

你应该做什么:将 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)

enter image description here

编辑:

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

enter image description here

关于r - 具有连续彩虹颜色的热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49689069/

相关文章:

android - 使用 Android Google Maps API 显示热图图层

r - 使用两个数据框创建 geom_tile 图

r - 正确扩展 ggplot2 吗?

r - 出现后结束动画

r - 基于应用函数命名 R 中的列表元素

r - Tidyeval 拼接运算符!!! ggplot 的 aes 失败

c++ - 使用 C++ 从不同大小的 blob 生成热图

r - 当数据更改时,ggvis 中的 linked_brush 无法在 Shiny 中工作

r - 更改轴标签的颜色

r - 如何正确创建这种情节