Change colors of raster plot in ggplot2

13,971

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

Share:
13,971

Related videos on Youtube

vitale232
Author by

vitale232

Updated on June 04, 2022

Comments

  • vitale232
    vitale232 almost 2 years

    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!

Related