I need to create a few raster figures, but keeping color ramp scale the same, but I also want the color ramp to be a smooth gradient. Is it possible to keep a big number of colors(~100 to have a smooth color ramp), but at the same time have a reasonable number of breaks, so that it's readable?
library(raster)
library(colorRamps)
r1<- raster(ncol=56, nrow=26)
r1[] <- runif(n=56*26,min=-20,max=15)
r2<- raster(ncol=56, nrow=26)
r2[] <- runif(n=56*26,min=-14,max=68)
brk=seq(-50,70,length.out=100)
col=matlab.like(100)
plot(r1, breaks=brk, col=col)
plot(r2, breaks=brk, col=col)
In this case I have a color ramp I wish, but you can't read the breaks labels
And when I decrease the number of breaks, the color ramp becomes all in one color
brk=seq(-50,70,length.out=6)
You might find this easier with ggplot2
. In the code below the key is, for each plot, to set the same color values for low
, mid
, and high
and the same limits
in scale_fill_gradient2
. That guarantees the same data values are mapped to the same colors in each plot. For example:
library(rasterVis)
library(ggplot2)
# Reproducible rasters
set.seed(4598)
r1<- raster(ncol=56, nrow=26)
r1[] <- runif(n=56*26,min=-20,max=15)
r2<- raster(ncol=56, nrow=26)
r2[] <- runif(n=56*26,min=-14,max=68)
# Get range of data values across the two rasters
rng = range(c(getValues(r1), getValues(r2)))
gplot(r1) +
geom_tile(aes(fill=value)) +
ggtitle("r1") +
scale_fill_gradient2(low="red", mid="green", high="blue",
midpoint=mean(rng), # Value that gets the middle color (default is zero)
breaks=seq(-100,100,10), # Set whatever breaks you want
limits=c(floor(rng[1]), ceiling(rng[2]))) # Set the same limits for each plot
gplot(r2) +
geom_tile(aes(fill=value)) +
ggtitle("r2") +
scale_fill_gradient2(low="red", mid="green", high="blue",
midpoint=mean(rng), # Value that gets the middle color (default is zero)
breaks=seq(-100,100,10), # Set whatever breaks you want
limits=c(floor(rng[1]), ceiling(rng[2]))) # Set the same limits for each plot