I have a 2x3 raster in R, with values 1 to 6.
library(raster)
r <- raster(nrows=3,ncols=2,xmn=0,xmx=2,ymn=0,ymx=3,vals=1:6)
colors <- c('red','orange','yellow','green','blue','purple')
plot(r,col=colors)
Now if I clip the raster, leaving the first two values out (red and orange), the color palette becomes useless.
r1 <- crop(r,extent(c(0.5,1.5,0.5,1.5)))
plot(r1,col=colors)
Notice how the extent
includes only the colors yellow, green, blue and purple from the first picture. However, these are not the colors in the second picture. The numbers in the raster are correct.
> values(r)
[1] 1 2 3 4 5 6
> values(r1)
[1] 3 4 5 6
How can I use the same color variable (colors
) in both cases in a consistent way?
My real world problem is cropping a world raster into country maps, using the same vegetation color code.
zlim
) ofc(1, 6)
, so you can get the same result withplot(crop(r,extent(c(0.5,1.5,0.5,1.5))), col = colors, zlim = c(1,6))
. Whether that will work with other palette choices is unclear though, you can control more specifically with thebreaks
argument.help(raster::ratify)
zlim
apparently solved my problem.