ggplot2 热图,带有范围值的颜色 [英] ggplot2 heatmap with colors for ranged values
问题描述
我想在 ggplot2 中制作热图.我的玩具数据和代码是:
I want to make a heatmap in ggplot2. My toy data and code is:
set.seed(12345)
dat <-
data.frame(
Row = rep(x = LETTERS[1:5], times = 10)
, Col = rep(x = LETTERS[1:10], each = 5)
, Y = rnorm(n = 50, mean = 0, sd = 1)
)
library(ggplot2)
p <- ggplot(data = dat, aes(x = Row, y = Col)) +
geom_tile(aes(fill = Y), colour = "white") +
scale_fill_gradient(low = "white", high = "steelblue")
p
我想要这样的范围值的配色方案:
I want to have color scheme for ranged values like this:
-3 <= Y < -2 ---> Dark Blue
-2 <= Y < -1 ---> Blue
-1 <= Y < 0 ---> Light Blue
0 <= Y < 1 ---> Light Green
1 <= Y < 2 ---> Green
2 <= Y <= 3 ---> Dark Green
推荐答案
对于此类问题,您有多种选择,但这里只是一个起点.
You have several options for something like this, but here is one as a starting point.
首先,使用 cut
从 Y
创建一个具有适当范围的因子:
First, use cut
to create a factor from Y
with the appropriate ranges:
dat$Y1 <- cut(dat$Y,breaks = c(-Inf,-3:3,Inf),right = FALSE)
然后使用来自 RColorBrewer 的调色板进行绘图:
Then plot using a palette from RColorBrewer:
ggplot(data = dat, aes(x = Row, y = Col)) +
geom_tile(aes(fill = Y1), colour = "white") +
scale_fill_brewer(palette = "PRGn")
这种配色方案在低端比蓝色更紫色,但它是我在啤酒调色板中能找到的最接近的.
This color scheme is more purple than blue on the low end, but it's the closest I could find among the brewer palette's.
如果您想构建自己的,您可以简单地使用 scale_fill_manual
并为 values
参数指定所需的颜色向量.
If you wanted to build your own, you could simply use scale_fill_manual
and specify your desired vector of colors for the values
argument.
这篇关于ggplot2 热图,带有范围值的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!