How to Use Contextily for High-Quality Geospatial Mapping in Python
- Jun 12
- 4 min read
Updated: Jun 23
Geospatial data visualization is an integral part of the current data science ecosystem, which consists of GIS (Geographic Information Systems), urban planning, environmental studies, transportation modeling, and location intelligence. While the spatial analytic capabilities of several of the available Python libraries (e.g., GeoPandas and Matplotlib) allow for relatively easy access to spatial analysis, producing professional-quality maps often requires the integration of high-resolution basemaps.
This is where Contextily comes in.
Contextily allows Python developers and GIS professionals to use web-based basemaps from web services like OpenStreetMap, CartoDB, Stamen, Esri, and other XYZ tile-based services directly within their Matplotlib and GeoPandas workflows. In particular, by retrieving and aligning tiles according to their projected coordinates, Contextily allows for an overall enhancement of geospatial output visual appeal and ability to be interpreted.

What Is Contextily?
Contextily is a Python library developed to provide web map tiles (as basemaps) for geospatial visualizations.
Seamless integration with:
In using it, you are able to retrieve map tiles from various online datasets and place them in the correct position with respect to your spatial data, giving you the means to produce high-quality maps with little coding effort.
Key functionality:
High-resolution basemap
Automatic download of tiles
Support for per-tile CRS transformation
Support for multiple tile providers
Offline storage of map tiles
Integration with GeoPandas workflow
Support for custom XYZ tiles
Why Use Contextily?
Without Contextily, GeoPandas maps often appear as plain vector plots with little geographic context.
For example:
gdf.plot()This generates a basic geometry visualization but lacks roads, landmarks, terrain, and other reference features.
With Contextily:
import contextily as ctx
ax = gdf.plot(figsize=(10, 10))
ctx.add_basemap(ax)The result is a professional map enriched with real-world geographic context.
Benefits include:
Enhanced spatial interpretation
Better stakeholder communication
Improved map aesthetics
Publication-ready visualizations
Reduced GIS software dependency
Installing Contextily
Install Contextily using pip:
pip install contextilyFor Conda users:
conda install -c conda-forge contextilyInstall supporting geospatial libraries:
pip install geopandas rasterio pyproj shapelyVerify installation:
import contextily as ctx
print(ctx.__version__)Understanding Coordinate Reference Systems (CRS)
One of the most important concepts when working with Contextily is coordinate reference systems.
Most online basemaps use:
EPSG:3857Also known as:
Web Mercator
Pseudo-Mercator
Spherical Mercator
GeoPandas datasets may use:
EPSG:4326Which stores:
Latitude
Longitude
Before adding a basemap, convert your GeoDataFrame:
gdf = gdf.to_crs(epsg=3857)Check CRS:
print(gdf.crs)Expected output:
EPSG:3857Failure to align CRS values is the most common cause of basemap rendering issues.
Creating Your First Contextily Map
Load Geospatial Data
import geopandas as gpd
gdf = gpd.read_file("cities.geojson")Convert CRS:
gdf = gdf.to_crs(epsg=3857)Plot data:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(12, 8))
gdf.plot(
ax=ax,
color="red",
markersize=50
)Add basemap:
import contextily as ctx
ctx.add_basemap(ax)Display map:
plt.show()Using Different Basemap Providers
Contextily supports multiple tile providers through the xyzservices ecosystem.
OpenStreetMap
ctx.add_basemap(
ax,
source=ctx.providers.OpenStreetMap.Mapnik
)Best for:
General mapping
Road networks
Urban visualization
CartoDB Positron
ctx.add_basemap(
ax,
source=ctx.providers.CartoDB.Positron
)Best for:
Data dashboards
Analytical maps
Minimalist cartography
CartoDB Dark Matter
ctx.add_basemap(
ax,
source=ctx.providers.CartoDB.DarkMatter
)Best for:
Dark-themed dashboards
Interactive visualizations
Data overlays
Adding High-Resolution Basemaps
For publication-quality outputs:
ctx.add_basemap(
ax,
source=ctx.providers.CartoDB.Positron,
zoom=15
)Export at high DPI:
plt.savefig(
"map.png",
dpi=300,
bbox_inches="tight"
)For scientific journals:
dpi=600is often recommended.
Custom Tile Servers
Contextily supports custom XYZ services.
Example:
ctx.add_basemap(
ax,
source="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
)This enables integration with:
Internal GIS servers
Enterprise map services
Specialized cartographic layers
Working with GeoPandas and Contextily
A common workflow combines:
Matplotlib
Example:
fig, ax = plt.subplots(
figsize=(14, 10)
)
gdf.plot(
ax=ax,
column="population",
cmap="viridis",
legend=True
)
ctx.add_basemap(
ax,
source=ctx.providers.CartoDB.Positron
)
plt.show()This creates a thematic choropleth map with geographic context.
Optimizing Performance
Large datasets can impact rendering performance.
Reduce Geometry Complexity
gdf["geometry"] = gdf.geometry.simplify(
tolerance=10
)Limit Map Extent
ax.set_xlim(
xmin,
xmax
)
ax.set_ylim(
ymin,
ymax
)Contextily is a key component of the Python geospatial ecosystem for building visually attractive, high-quality maps, and forms an integral part of your GeoPandas and Matplotlib workflows for embedding third-party web-based basemaps into those workflows. As such, it allows users such as data scientists, GIS analysts, researchers, and engineers to enhance their basic spatial plots with professional-looking cartographic products.
Whether you are creating dashboards for urban analytics, monitoring systems for the environment, transportation models, location intelligence platforms, or visualizations for scientific purposes, you will be able to use Contextily to add a geographic context to your geospatial visualizations in an efficient and easily scalable manner. If you also have a good understanding of CRS management and can use the optimised zoom levels and high-quality exported files that Contextily supports, then you can produce enterprise-class geospatial visualisations starting with basic vector-based visualisations and transforming them into mapping solutions that can be used for reports, presentations, publications, and production applications.
To learn more about Contextily and its geospatial capabilities, click here.
For more information or any questions regarding Contextily, please don't hesitate to contact us at
Email: info@geowgs84.com
USA (HQ): (720) 702–4849
(A GeoWGS84 Corp Company)




Comments