Contextily
Contextily is a Python library (v1.7.0) for adding context geo-tiles as basemaps to Matplotlib figures or saving them as geospatial raster files. It is actively developed, with minor releases every few months, and is tightly integrated with GeoPandas and the `xyzservices` package for tile providers.
Warnings
- breaking The `plot_map` function was deprecated in previous versions and has been entirely removed in `contextily` v1.7.0.
- breaking The default tile provider changed from Stamen to OpenStreetMap Humanitarian in v1.4.0. This change was due to Stamen moving under Stadia and requiring an API key. Users expecting Stamen tiles will now get OpenStreetMap Humanitarian by default.
- breaking Contextily now requires Python 3.10 or newer. Older Python versions are no longer supported.
- gotcha Web map tiles are typically in Web Mercator (EPSG:3857). If your data is in a different Coordinate Reference System (CRS), you must either reproject your data to EPSG:3857 before plotting or pass your data's CRS to `cx.add_basemap` using the `crs` parameter for on-the-fly warping. Not doing so can lead to misaligned basemaps.
Install
-
pip install contextily -
conda install contextily --channel conda-forge
Imports
- add_basemap
import contextily as cx cx.add_basemap(ax, ...)
- providers
import contextily as cx cx.providers.OpenStreetMap.Mapnik
Quickstart
import geopandas
import contextily as cx
import matplotlib.pyplot as plt
# Load a sample GeoDataFrame
df = geopandas.read_file(geopandas.datasets.get_path("nybb"))
# Ensure the data is in Web Mercator (EPSG:3857) or set the crs parameter in add_basemap
df_wm = df.to_crs(epsg=3857)
# Plot the GeoDataFrame
fig, ax = plt.subplots(figsize=(10, 10))
df_wm.plot(ax=ax, alpha=0.5, edgecolor="k", facecolor="cyan")
# Add a basemap
cx.add_basemap(ax, crs=df_wm.crs)
# Optional: Customize the title and display
ax.set_title("NYC Boroughs with Contextual Basemap")
plt.tight_layout()
plt.show()