Contextily

1.7.0 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `contextily` with `geopandas` to add a web tile basemap to a geospatial plot. It loads the NYC boroughs dataset, reprojects it to Web Mercator (EPSG:3857) which is standard for web tiles, plots the data, and then overlays a basemap using `cx.add_basemap()`.

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()

view raw JSON →