r-tmap / tmap

R package for thematic maps
https://r-tmap.github.io/tmap
GNU General Public License v3.0
862 stars 121 forks source link

tm_raster not working with stars objects following st_geotransform in tmap v4 #818

Open marine-ecologist opened 9 months ago

marine-ecologist commented 9 months ago

I'm having an issue mapping stars objects under tmap v4:

Error in UseMethod("st_as_sf") : 
  no applicable method for 'st_as_sf' applied to an object of class "dimensions"
In addition: Warning messages:
1: In st_coordinates.stars(x, add_max = add_max, center = center, ...) :
  center values are given for spatial coordinates
2: Unable to warp stars. Stars will be transformed now (which will take some time). 

see reproducible example that fails with raster.warp set with both TRUE and FALSE:

library(stars)
m = matrix(1:20, 4)
s0 = st_as_stars(m)
s = s0
st_crs(s) <- 4326
st_crs(s0) <- 4326

st_geotransform(s0) <- c(5, 1.5, 0.2, 0, 0.2, 1.5)

library(tmap)
tmap_mode("plot") 
tm_shape(s) +
  tm_raster(col_alpha=0.5) +
tm_shape(s0,raster.warp = FALSE) 

Previously this worked with tmap v3 when tmap_mode("view"):

Screenshot 2023-12-30 at 6 00 22 am

but not with tmap_mode("plot"):

Screenshot 2023-12-30 at 6 00 34 am
mtennekes commented 8 months ago

This issue is partly solved (took me a looong time) https://github.com/r-tmap/tmap/commit/f0a9205a58b2225d352135e2855643d14a85db72

Now looking at the geotransformation:

library(stars)
#> Loading required package: abind
#> Loading required package: sf
#> Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(mapview)
m = matrix(1:20, 4)
s0 = st_as_stars(m)
s = s0
st_crs(s) <- 4326
st_crs(s0) <- 4326
st_geotransform(s0) <- c(5, 1.5, 0.2, 0, 0.2, 1.5)

s0_4326 = st_transform(s0, crs = 4326)

stars:::is_curvilinear(s0)
#> [1] FALSE
stars:::is_curvilinear(s0_4326)
#> [1] TRUE

s0
#> stars object with 2 dimensions and 1 attribute
#> attribute(s):
#>     Min. 1st Qu. Median Mean 3rd Qu. Max.
#> A1     1    5.75   10.5 10.5   15.25   20
#> dimension(s):
#>    from to offset delta refsys point x/y
#> X1    1  4      5   1.5 WGS 84 FALSE [x]
#> X2    1  5      0   1.5 WGS 84 FALSE [y]
#> sheared raster with parameters: 0.2 0.2
s0_4326
#> stars object with 2 dimensions and 1 attribute
#> attribute(s):
#>     Min. 1st Qu. Median Mean 3rd Qu. Max.
#> A1     1    5.75   10.5 10.5   15.25   20
#> dimension(s):
#>    from to refsys point               values x/y
#> X1    1  4 WGS 84 FALSE [4x5] 5.85,...,11.15 [x]
#> X2    1  5 WGS 84 FALSE  [4x5] 0.85,...,7.45 [y]
#> curvilinear grid

Currently, the curvilinear gridded stars work well in tmap, but the sheared gridded stars not (yet). So as workaround I might do a st_transformation to obtain a curvilinear grid.

@edzer do you have any tips how to deal with this efficiently?