What I want to do is combining a few different raster files of crop harvest (e.g. for soybean and maize) into one map. The legend should show two different colors for the crops. The data I will be using is this crop map data: http://www.earthstat.org/harvested-area-yield-175-crops/
But first I am trying to do this on a sample data set:
library(raster)
r1 <- raster(nrow=10, ncol=10)
r1[] = sample(c(0,1), 100, replace = TRUE)
r1 <- ratify(r1)
rat <- levels(r1)[[1]]
rat$landcover <- c('NA', 'Maize')
rat$class <- c('A1', 'B2')
levels(r1) <- rat
r2 <- raster(nrow=10, ncol=10)
r2[] = sample(c(0,2), 100, replace = TRUE)
r2 <- ratify(r2)
rat <- levels(r2)[[1]]
rat$landcover <- c('NA', "Soybean")
rat$class <- c('A1', 'C3')
levels(r2) <- rat
If I levelplot these two it looks good
levelplot(r1, col.regions = c('white', 'blue'))
levelplot(r2, col.regions = c('white', 'green'))
But then I try to combine them and I get a weird result
rm = merge(r1,r2)
levelplot(rm, col.regions=c('white', 'blue', 'green'))
Any ideas where I did wrong?
It's not clear how you would like to combine these, though it would be straightforward to convert them to data frames to plot in ggplot
:
df <- rbind(cbind(as.data.frame(rasterToPoints(r1)), raster = "r1"),
cbind(as.data.frame(rasterToPoints(r2)), raster = "r2"))
df$layer[df$layer == 0] <- NA
df$layer <- factor(c("Maize", "Soybean")[df$layer])
library(ggplot2)
ggplot(df, aes(x, y, fill = layer)) +
geom_tile(na.rm = TRUE, alpha = 0.3) +
scale_fill_manual(values = c("red", "forestgreen"), na.value = NA) +
theme_bw()