在ggplot2中更改栅格图的颜色

vit*_*232 9 gis plot r ggplot2

我试图使用ggplot2而不是光栅包绘图功能制作光栅图,原因有些不相关.

我想缩放颜色,使图上的最低温度为蓝色,图上的最高温度为红色,而中间范围为白色.我已经尝试了ggplot2的众多功能,但我一直未能获得理想的结果.这就是我要的:

从光栅包中显示所需颜色渐变的图

这是我的ggplot2代码的当前状态:

library(raster)
library(ggplot2)
library(scales)

r = raster()
r[] = 1:ncell(r)

df = as.data.frame(r, xy=TRUE)

the_plot = ggplot(df) + 
  geom_raster(aes(x, y, fill=layer)) +
  scale_fill_gradient2(low=muted('red'), mid='white', high=muted('blue'))
print(the_plot)
Run Code Online (Sandbox Code Playgroud)

哪个,而不是所需的颜色渐变,产生这个:

ggplot2 scale_fill_gradient2()失败

任何建议都非常感谢!

akh*_*med 9

刚刚尝试了您的示例数据集,以下代码适合我.

the_plot = ggplot(df) + 
  geom_raster(aes(x, y, fill=layer)) +
  scale_fill_gradientn(colours=c("#0000FFFF","#FFFFFFFF","#FF0000FF"))
print(the_plot)
Run Code Online (Sandbox Code Playgroud)

需要根据蓝色/红色的精确色调调整RGB颜色,但它似乎有效.

显示结果的图表