2

I am using ggplot2 to plot maps that have the same extent (i.e. same spatial coverage) but that show different features.

This is how it looks like:

library(raster)
library(reshape2)
library(ggplot2)

# make-up data
r <- raster(system.file("external/test.grd", package="raster"))
s <- stack(r, r**2, r**3, r**4, r**5)
names(s) <- paste0("Field ",seq(1,5))

# convert to data frame
rast.df <- as.data.frame(s, xy=T)

# melt 
rast.melt <- melt(rast.df, id.vars = c('x','y'), variable.name="field")

# plot
ggplot() +
  geom_raster(data=rast.melt , aes(x=x, y=y, fill=value)) +
  facet_wrap(~field) +
  scale_fill_continuous(na.value="transparent")

enter image description here

The resulting figure looks quite crappy because there's one single legend for all the maps. Therefore, the maps have no contrast at all.

How can I use individual legends for each facet in the graph above?

thiagoveloso
  • 2,537
  • 3
  • 28
  • 57

1 Answers1

4

Here's an approach with ggarrange from the ggpubr package:

library(ggpubr)
ggarrange(plotlist = lapply(split(rast.melt, rast.melt$field),function(x){
                     ggplot() + geom_raster(data=x , aes(x=x, y=y, fill=value)) +
                       scale_fill_continuous(na.value="transparent") + 
                       ggtitle(x$field[1])}))

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
  • Awesome! Is there any way to "center" the two bottom plots, like I ask in this other question? https://stackoverflow.com/questions/62721800/ggplot2-customize-facet-position?noredirect=1#comment110917382_62721800 – thiagoveloso Jul 03 '20 at 21:42
  • 1
    If there is, it's not obvious to me how to do it. `ggarrange` is convenience wrapper around [`cowplot::plot_grid`](https://rdrr.io/cran/cowplot/man/plot_grid.html). You could try that if it's a dealbreaker. – Ian Campbell Jul 03 '20 at 21:55
  • 1
    @thiagoveloso you can try patchwork, but no simple way to do it. Just save in PDF and modify manually. – Herman Toothrot Nov 20 '22 at 18:25