Tint Band - R, leaflet, sf - Header

Polygons tint band with leaflet and simple feature (library sf)

Add a tint band (aka shapeburst fill) in leaflet

Stackoverflow is again a source of inspiration. I found this question on tint bands in leaflet, not related to R originally but I though I could answer it with R easily. This is also a good one for me to play with this new simple feature library sf and use it with leaflet.
My simple solution is to create a new multipolygon from the original one, but with holes inside, so that we only get a doughnut polygon for each area. As raised by my question on stackoverflow (again…), I recently remarked that it could be tricky to plot multipolygons with holes in ggplot2 with SpatialPolygons from library sp, which is another reason to use library sf.

Get French regions data

Let’s use some French regions polygons and attribute one colour to each region. I like piratepal colours of library yarrr.

Tint Band - Regions

Create future holes with buffer

We create the future holes with a smaller buffer area.
Here, st_buffer returns an object without geometry type (geometry type: GEOMETRY), which prevents it to be plot (Error in CPL_gdal_dimension(st_geometry(x), NA_if_empty)). A workaround is to use st_cast after.

Tint Band - Holes

Create holes in the original polygons

To create the doughnuts using original and buffer polygons, I used st_difference. However as discussed with edzer in the sf github repository, I had to transform the buffer polygons into a Multipolygon of a unique Multipolygon using st_combine. Moreover, because the resulting Multipolygon object as no identified geometry, I had to pass it through st_cast.

Tint Band - library sf - Doughnuts

Output tint bands in leaflet

Now we can use it to produce a leaflet map with tinted bands having transparency and original polygons in black. (To allow for a quick view, polygons were simplified with st_simplify. You’ll see it if you zoom. Simplification according to regions is shown in the complete script below)

The full rmarkdown script

If you want to reproduce these figures, you can copy the full rmarkdown script below.