paleolimbot / ggspatial

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

Add `terra` support #91

Closed dieghernan closed 3 years ago

dieghernan commented 3 years ago

Hi:

I think the package doesn’t support yet SpatRaster objects. Would it be possible to work on this?

Regards

dieghernan commented 3 years ago

So a workaround proposed by @dominicroye on this FANTASTIC post (don't miss it): https://dominicroye.github.io/en/2021/firefly-cartography/ is to convert it back to a RasterStack and it works.

Still I think it could be a good improvement for the package,

library(ggplot2)
library(ggspatial)

load_longlake_data()

is_raster <- longlake_osm

is_raster

## class      : RasterBrick 
## dimensions : 471, 553, 260463, 3  (nrow, ncol, ncell, nlayers)
## resolution : 3.33, 3.32  (x, y)
## extent     : 409891.4, 411732.9, 5083289, 5084853  (xmin, xmax, ymin, ymax)
## crs        : +proj=utm +zone=20 +datum=NAD83 +units=m +no_defs 
## source     : longlake.tif 
## names      : longlake.1, longlake.2, longlake.3 
## min values :         25,         74,         46 
## max values :        255,        255,        255

ggplot() +
  layer_spatial(is_raster) +
  labs(title = class(is_raster))

setup-1

library(terra)

## Warning: package 'terra' was built under R version 4.1.1

## terra version 1.4.7

is_spatraster <- terra::rast(is_raster)

is_spatraster

## class       : SpatRaster 
## dimensions  : 471, 553, 3  (nrow, ncol, nlyr)
## resolution  : 3.33, 3.32  (x, y)
## extent      : 409891.4, 411732.9, 5083289, 5084853  (xmin, xmax, ymin, ymax)
## coord. ref. : NAD83 / UTM zone 20N (EPSG:26920) 
## source      : longlake.tif 
## red-grn-blue: 1, 2, 3 
## names       : lon_1, lon_2, lon_3 
## min values  :    25,    74,    46 
## max values  :   255,   255,   255

# This won't work
try(ggplot() +
  layer_spatial(is_spatraster))

## Error in UseMethod("st_as_sf") : 
##   no applicable method for 'st_as_sf' applied to an object of class "SpatRaster"

# Stack with raster
stack_spatraster <- raster::stack(is_spatraster)
stack_spatraster

## class      : RasterStack 
## dimensions : 471, 553, 260463, 3  (nrow, ncol, ncell, nlayers)
## resolution : 3.33, 3.32  (x, y)
## extent     : 409891.4, 411732.9, 5083289, 5084853  (xmin, xmax, ymin, ymax)
## crs        : +proj=utm +zone=20 +datum=NAD83 +units=m +no_defs 
## names      : longlake.1, longlake.2, longlake.3 
## min values :         25,         74,         46 
## max values :        255,        255,        255

# This would work
ggplot() +
  layer_spatial(stack_spatraster) +
  labs(
    title = class(is_spatraster),
    subtitle = paste(
      "Converted to ",
      class(stack_spatraster)
    )
  )

setup-2

choc2000 commented 2 years ago

I'm very much interested in terra support. Is there any plans yet when this would make it into a CRAN release? Thanks!