Build a regular grid based on an sf object or a SpatialPolygonsDataFrame.

getGridLayer(x, cellsize, type = "regular", var)

Arguments

x

an sf object, a simple feature collection or a SpatialPolygonsDataFrame.

cellsize

targeted area of the cell, in map units.

type

shape of the cell, "regular" for squares, "hexagonal" for hexagons.

var

name of the numeric variable(s) in x to adapt to the grid (a vector).

Value

A grid is returned as an sf object.

Examples

library(sf)
mtq <- st_read(system.file("gpkg/mtq.gpkg", package="cartography"))
#> Reading layer `mtq' from data source 
#>   `/tmp/RtmpmpfIrO/temp_libpath18ee15f22a9e/cartography/gpkg/mtq.gpkg' 
#>   using driver `GPKG'
#> Simple feature collection with 34 features and 7 fields
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 690574 ymin: 1592536 xmax: 735940.2 ymax: 1645660
#> Projected CRS: WGS 84 / UTM zone 20N
# Plot dentsity of population
mtq$POPDENS <- 1e6 * mtq$POP / st_area(mtq) 
bks <- getBreaks(v = mtq$POPDENS, method = "geom", 5)
cols <- carto.pal(pal1 = "taupe.pal", n1 = 5)
opar <- par(mfrow = c(1,2), mar = c(0,0,0,0))
choroLayer(x = mtq, var = "POPDENS", breaks = bks,
           border = "burlywood3", col = cols,
           legend.pos = "topright", legend.values.rnd = 0,
           legend.title.txt = "Population density")

mygrid <- getGridLayer(x = mtq, cellsize = 3e7,
                       type = "hexagonal", var = "POP")
## conversion from square meter to square kilometers
mygrid$POPDENSG <- 1e6 * mygrid$POP / mygrid$gridarea 
choroLayer(x = mygrid, var = "POPDENSG", breaks = bks,
           border = "burlywood3", col = cols,
           legend.pos = "n", legend.values.rnd = 1,
           legend.title.txt = "Population density")

par(opar)