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:
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!
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.
By default, ggplot2 chooses to use a specific shade of red, green, and blue for the bars.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With