Search code examples
pythongeoviews

GeoViews: adding a tile basemap using matplotlib backend


Using the matplotlib backend, is it possible to add a tile basemap such as OSM to a GeoViewsplot, e.g. by somehow calling contextily? Using the Bokeh backend, this is done via gv.tile_sources and then adding it to an overlay but is there a similar function for the mpl backend?

Post-answer edit

Adding a reproducible example assuming one is switching between backends, and using neighbourhood-level polygon gdfs in EPSG:4326.

What made me initially think adding a basemap was not possible was (1) not defining the WMTS zoom level (causing undecipherable pixelated text to be plotted instead of features), and, after reading James' answer, (2) adding the tiles layer to the layout last, not first, which caused tiles to cover the polygons layers (not an issue on the bokeh backend, but with matplotlib apparently it does matter).

import geoviews as gv
from geoviews import opts
from cartopy import crs as ccrs

gv.extension('bokeh', 'matplotlib')

tiles = gv.tile_sources.OSM()

layout = tiles * gv.Polygons(gdf1, group="group1") * gv.Polygons(gdf2, group="group2")

layout.opts(
            opts.Polygons('group1', cmap=['red'], backend="matplotlib"),
            opts.Polygons('group2', cmap=['lightgrey'], backend="matplotlib"),
            opts.Overlay(backend='matplotlib'),
            opts.WMTS(zoom=13, backend='matplotlib'),
            projection=ccrs.Mercator()
        )
        
gv.output(layout, size=500, fig='svg', backend='matplotlib')

Solution

  • Sure, same as for Bokeh:

    import geoviews as gv
    from geoviews import opts, tile_sources as gvts
    gv.extension('matplotlib')
    
    opts.defaults(
        opts.Layout(sublabel_format='', vspace=0.1, hspace=0.1, fig_size=200),
        opts.WMTS(zoom=0))
    
    (gvts.Wikipedia + gvts.StamenToner + gvts.EsriNatGeo + gvts.EsriImagery +
     gvts.EsriUSATopo + gvts.EsriTerrain + gvts.EsriReference + gvts.StamenTerrain).cols(4)
    

    enter image description here