Plotting many rasters using the same color scale in ggplot2

209 views
Skip to first unread message

gafna jeff

unread,
Mar 21, 2022, 5:58:03 AM3/21/22
to ggplot2

 In this reproducible code am am downloading bioclim variables and plotting two bioclim variables (bio17 and bio19). However, I would like to plot the two variables using the same color scale. Could anyone give me a hint on how to do this in ggplot2. Below is my code. I would appreciate your help.

library(raster)
library(sp)

#Download bioclim variables
r <- getData("worldclim",var="bio",res=10)
plot(r)
names(r)

#Select variables 17 and 19
r <- r[[c(17,19)]]
plot(r)


#convert the raster into dataframe for use in ggplot
rdf <- as.data.frame(r, xy=TRUE)
names(rdf)
head(rdf)
names(rdf)

names(rdf)[4] <- 'ppt_coldest_quarter'

ppt_coldest_quarter <- ggplot()+
  geom_raster(mapping=aes(x=x, y=y, fill=ppt_coldest_quarter), data = rdf) + scale_fill_viridis_c(name="Bio19 (mm)", direction = 1) + coord_quickmap() + theme(legend.position = c(0.78, 0.78))  + theme(panel.border = element_rect(colour = "black", fill="NA", size=1)) + theme(plot.margin = unit(c(0, 0, 0, 0), "lines")) + theme(legend.title = element_text(size = 9), legend.text = element_text(size = 8)) + theme(panel.background = element_rect(fill = "white", color = "white")) + theme(panel.border = element_blank(), axis.text = element_blank(), panel.grid = element_blank(), axis.ticks = element_blank()) + labs(x="", y="")


names(rdf)[3] <- 'ppt_driest_quarter'

ppt_driest_quarter <- ggplot()+
  geom_raster(mapping=aes(x=x, y=y, fill=ppt_driest_quarter), data = rdf) + scale_fill_viridis_c(name="Bio16 (mm)", direction = 1) + coord_quickmap() + theme(legend.position = c(0.78, 0.78))  + theme(panel.border = element_rect(colour = "black", fill="NA", size=1)) + theme(plot.margin = unit(c(0, 0, 0, 0), "lines")) + theme(legend.title = element_text(size = 9), legend.text = element_text(size = 8)) + theme(panel.background = element_rect(fill = "white", color = "white")) + theme(panel.border = element_blank(), axis.text = element_blank(), panel.grid = element_blank(), axis.ticks = element_blank()) + labs(x="", y="")



Reply all
Reply to author
Forward
0 new messages