R热图:为值指定颜色 [英] R heatmap: assign colors to values
本文介绍了R热图:为值指定颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在热图的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。现在我想为这些值分配定义的颜色F.E.详情如下:
-1:红色,0:绿色,1:黄色,2:蓝色。
有没有办法使用geom_tile函数来解决我的问题?
谢谢!
推荐答案
如果希望具有离散的间隔和比例,则应将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')
这篇关于R热图:为值指定颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文