paleolimbot / ggspatial

Enhancing spatial visualization in ggplot2
https://paleolimbot.github.io/ggspatial
368 stars 34 forks source link

Add support for factor/categorical rasters #78

Closed JoshOBrien closed 3 years ago

JoshOBrien commented 3 years ago

This commit makes it possible to plot factor/categorical rasters using layer_spatial.Raster(). It does so by testing whether the supplied raster is a factor raster and, if it is, using the raster's raster attribute table (RAT) to convert the appropriate value column(s) in the data.frame that's ultimately passed along to ggplot2::geom_raster() to a factor. For now, the RAT's first two columns (its ID column and its first value column) are used to define the mapping of the raster's values to the appropriate factor labels.

Following is a simple example of the type of plot this edit makes possible:

library(ggplot2)
library(ggspatial)
library(sf)
library(raster)

lux <- st_read(system.file("external", package = "raster"), "lux") %>%
    st_transform(32632)
r <- raster(extent(lux), resolution = c(3000, 3000))
lux <- rasterize(lux[, c("NAME_2", "NAME_1")], r)

ggplot() + layer_spatial(lux) +
    scale_fill_brewer(palette = "Paired",
                      na.value = NA, na.translate = FALSE,
                      expand = c(0, 0)) +
    labs(fill = "Province")
JoshOBrien commented 3 years ago

FWIW, the "All checks failed" message attached to my PR was caused by a failure to install rgdal in the "Install dependencies" step rather than anything in the PR.

JoshOBrien commented 3 years ago

@paleolimbot Glad you are open to adding these tweaks to your terrific package!

I went ahead and added some tests, plus made the formatting changes you requested. Let me know if you need me to make any additional changes.

Cheers.

paleolimbot commented 3 years ago

Thanks!