1

我在 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。现在我想为这些值分配定义的颜色,fe如下:-1:红色,0:绿色,1:黄色,2:蓝色。

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

谢谢!

4

2 回答 2

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

在此处输入图像描述

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

在此处输入图像描述

于 2021-07-08T08:02:24.297 回答
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"))

这些颜色似乎产生了相当的景象 在此处输入图像描述

于 2021-07-08T07:59:41.847 回答