在ggplot2中更改栅格图的颜色 [英] Change colors of raster plot in ggplot2

查看:146
本文介绍了在ggplot2中更改栅格图的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某些不相关的原因,我正在尝试使用ggplot2而不是栅格数据包绘图功能来制作栅格图.

I am trying to make a raster plot using ggplot2 rather than the raster package plot function for some irrelevant reasons.

我想对颜色进行缩放,以使绘图上的最低温度为蓝色,绘图上的最高温度为红色,而中间范围为白色.我已经尝试过ggplot2的许多功能,但始终无法获得理想的结果.这就是我想要的:

I would like to scale the colors so that the minimum temperature on the plot is blue and the maximum temperature on the plot is red, while the mid range is white. I have tried numerous functions from ggplot2, and I keep failing to get the desired result. This is what I want:

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

Here is the current state of my ggplot2 code:

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)

哪个而不是所需的颜色渐变会产生以下结果:

Which, rather than the desired color ramp, produces this:

任何建议都将不胜感激!

Any suggestions are much appreciated!

推荐答案

只需尝试您的示例数据集,以下代码对我有用.

Just tried your example dataset and the following code works for me.

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

需要将RGB颜色调整为所需的确切蓝色/红色阴影,但这似乎可行.

RGB colors need to be adjusted for the exact desired shades of blue/red but it seems to work.

这篇关于在ggplot2中更改栅格图的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆