R 热图:为值分配颜色

时间:2021-07-08 07:49:21

标签: r heatmap geom-tile

我在 R 图形库 (https://www.r-graph-gallery.com/79-levelplot-with-ggplot2.html) 中找到了以下用于热图的 R 代码并对其进行了一些修改:

# Library
library(ggplot2)

set.seed(10)

# Dummy data
x <- LETTERS[1:20]
y <- paste0("var", seq(1,20))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(400, -1, 2)

print (data)

# Heatmap 
ggplot(data, aes(X, Y, fill= Z)) + 
  geom_tile(color = "white",
            lwd = 0.5,
            linetype = 1)

我的问题:我有三列,值范围从 -1 到 2。现在我想为这些值分配定义的颜色,例如如下: -1:红色,0:绿色,1:黄色,2:蓝色。

有没有办法使用 geom_tile 函数来解决我的问题?

谢谢!

2 个答案:

答案 0 :(得分:1)

如果你想有离散的间隔和尺度,你应该把 df$Z 的值转化为整数因子,然后使用 scale_fill_manual 来获得所需的配色方案。

data$Z <- factor(round(data$Z))

# Heatmap 
ggplot(data, aes(X, Y, fill= Z)) + 
    geom_tile(color = "white",
              lwd = 0.5,
              linetype = 1)+
    scale_fill_manual(values = c('red', 'green', 'yellow', 'blue'))

#or simply

ggplot(data, aes(X, Y, fill= factor(round(data$Z)))) + 
    geom_tile(color = "white",
              lwd = 0.5,
              linetype = 1)+
    scale_fill_manual(values = c('red', 'green', 'yellow', 'blue'), name = 'Z')

esp_netif_get_sta_list()

要将 Z 值转换为字符串,您可以使用:

library(plyr)

data$Z <- factor(round(data$Z))

ata$Z <- revalue(data$Z, c('-1'='negative'))
data$Z <- revalue(data$Z, c('0' = 'no'))
data$Z <- revalue(data$Z, c('1' = 'yes'))
data$Z <- revalue(data$Z, c('2' = 'other'))

# Heatmap 
ggplot(data, aes(X, Y, fill= Z)) + 
    geom_tile(color = "white",
              lwd = 0.5,
              linetype = 1)+
    scale_fill_manual(values = c('red', 'green', 'yellow', 'blue'), name = 'Z')

enter image description here

答案 1 :(得分:0)

你可以使用 scale_gradient_n

ggplot(data, aes(X, Y, fill= Z)) + 
  geom_tile(color = "white",
            lwd = 0.5,
            linetype = 1) + 
  scale_fill_gradientn(breaks=c(-1, 0, 1, 2), colors=c("red","green","yellow","blue"))

那些颜色似乎产生了相当的视觉效果 enter image description here

相关问题