Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change colors of raster plot in ggplot2

Tags:

plot

r

ggplot2

gis

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!

like image 702
vitale232 Avatar asked Apr 06 '15 18:04

vitale232


People also ask

How do you change colors in Ggplot?

Change colors manually A custom color palettes can be specified using the functions : scale_fill_manual() for box plot, bar plot, violin plot, etc. scale_color_manual() for lines and points.

What are the default colors in ggplot2?

By default, ggplot2 chooses to use a specific shade of red, green, and blue for the bars.

How do you add color to a geom point?

To color the points in a scatterplot using ggplot2, we can use colour argument inside geom_point with aes. The color can be passed in multiple ways, one such way is to name the particular color and the other way is to giving a range or using a variable.

How do you plot raster data?

Format Plot If we need to create multiple plots using the same color palette, we can create an R object ( myCol ) for the set of colors that we want to use. We can then quickly change the palette across all plots by simply modifying the myCol object. We can label the x- and y-axes of our plot too using xlab and ylab .


1 Answers

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

like image 56
akhmed Avatar answered Oct 16 '22 10:10

akhmed