因此,您可以使用RColorBrewer 或colorRampPalette 来实现此目的(或两者的组合)并设置breaks。
library(raster)
library(RColorBrewer)
breakpoints <- c(-2000, seq(0, 500, 55.6))
colors <- c("red", RColorBrewer::brewer.pal(9, "Blues"))
plot(r, breaks = breakpoints, col = colors)
输出
您也可以通过设置两种独特的颜色来使用 colorRampPalette 做类似的事情。然后,在括号中定义您想要的渐变颜色的数量。
colors <- c("red", colorRampPalette(c("steelblue1", "steelblue4"))(9))
您也可以将这两者结合使用。
colors <- c("red", colorRampPalette(RColorBrewer::brewer.pal(9, "Blues"))(11))
如果你想让红色也连续,那么你可以为两者创建一个渐变。
breakpoints <- c(seq(-2000, -1, 222), seq(0, 500, 55.6))
colors <- c(RColorBrewer::brewer.pal(9, "Reds"), RColorBrewer::brewer.pal(9, "Blues"))
plot(r, breaks = breakpoints, col = colors)
输出
使用ggplot 设置这些会更容易一些。您基本上需要在 0 到 1 的范围内重新调整值,以使 0 成为“中点”。
library(tidyverse)
library(ggplot2)
rdf <- as.data.frame(r, xy = TRUE)
rdf %>%
ggplot() +
geom_raster(aes(x, y, fill = layer)) +
scale_fill_gradientn(
colours = colorRampPalette(rev(RColorBrewer::brewer.pal(11, "RdBu")))(255),
values = c(1.0, (0 - min(rdf$layer)) / (max(rdf$layer) - min(rdf$layer)), 0)
)
输出