10
votes

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

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:

plot showing desired color ramp from raster package

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:

ggplot2 scale_fill_gradient2() fail

Any suggestions are much appreciated!

1
Care to share some data? so we can recreate the plot. Have you tried scale_fill_discrete or scale_fill_hue?infominer
Have you tried setting the midpoint argument to scale_fill_gradient2?Gregor Thomas

1 Answers

10
votes

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 colors need to be adjusted for the exact desired shades of blue/red but it seems to work.

plot showing the result