3D Maps in Python with pydeck (deck.gl)

Build interactive 3D maps with pydeck: a HexagonLayer of extruded columns, a ScatterplotLayer colored by a column, an ArcLayer for flows, tooltips, a basemap with no API key, and saving the map as HTML.

To make a 3D map in Python, describe your data as a layer with pdk.Layer("HexagonLayer", df, get_position=["lon", "lat"], extruded=True), put the layer in a pdk.Deck, and call deck.to_html("map.html"). pydeck is the Python binding for deck.gl, a WebGL library built for large datasets, so the browser does the drawing and the map stays smooth with tens of thousands of points. For flat maps, see Folium.

This post uses pydeck 0.9.3, which loads deck.gl 9.3 and MapLibre from a CDN, so the saved HTML needs an internet connection and a browser with WebGL. Install it with pip install pydeck.

Quick Example

The data is 5,000 simulated e-scooter trips in Austin, Texas, starting and ending around five busy spots (seeded, so you get the same map). The basemap is the USGS topographic map (drawn pale and gray so the data stands out), which is public domain and needs no API key. The last lines are the part to keep:

import json
from urllib.parse import quote

import numpy as np
import pandas as pd
import pydeck as pdk

rng = np.random.default_rng(52)
hubs = pd.DataFrame({  # center, spread (degrees) and share of trip starts
    "lat": [30.2653, 30.2849, 30.2478, 30.2620, 30.2985],
    "lon": [-97.7431, -97.7341, -97.7500, -97.7220, -97.7050],
    "spread": [0.0050, 0.0040, 0.0060, 0.0055, 0.0050],
    "share": [0.34, 0.24, 0.17, 0.15, 0.10],
}, index=["Downtown", "UT Campus", "South Congress", "East Austin", "Mueller"])
n = 5000
start = rng.choice(len(hubs), size=n, p=hubs["share"])
end = rng.choice(len(hubs), size=n, p=[0.40, 0.22, 0.14, 0.14, 0.10])
start_lat = hubs["lat"].to_numpy()[start] + rng.normal(0, 1, n) * hubs["spread"].to_numpy()[start]
start_lon = hubs["lon"].to_numpy()[start] + rng.normal(0, 1, n) * hubs["spread"].to_numpy()[start]
end_lat = hubs["lat"].to_numpy()[end] + rng.normal(0, 1, n) * hubs["spread"].to_numpy()[end]
end_lon = hubs["lon"].to_numpy()[end] + rng.normal(0, 1, n) * hubs["spread"].to_numpy()[end]
km = np.hypot((end_lat - start_lat) * 111, (end_lon - start_lon) * 96)
trips = pd.DataFrame({
    "origin": hubs.index[start], "dest": hubs.index[end],
    "start_lat": start_lat, "start_lon": start_lon,
    "minutes": (3 + 4.5 * km + rng.gamma(2, 1.5, n)).round(1),
})

# A basemap style that needs no API key: USGS topographic tiles through MapLibre
usgs = {"version": 8, "sources": {"usgs": {
    "type": "raster", "tileSize": 256, "attribution": "USGS The National Map",
    "tiles": ["https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}"]}},
        "layers": [{"id": "usgs", "type": "raster", "source": "usgs",  # pale and gray, so the data stands out
                    "paint": {"raster-saturation": -0.85, "raster-opacity": 0.7}}]}
basemap = "data:application/json," + quote(json.dumps(usgs))

hexagons = pdk.Layer(
    "HexagonLayer", trips,
    get_position=["start_lon", "start_lat"],  # longitude first
    radius=200, coverage=0.9,                 # hexagon radius in meters
    extruded=True, elevation_scale=3,         # column height = trips counted x 3 m
    color_range=[[255, 255, 204], [199, 233, 180], [127, 205, 187],
                 [65, 182, 196], [44, 127, 184], [37, 52, 148]],
    pickable=True,
)
view = pdk.ViewState(latitude=30.272, longitude=-97.735, zoom=12.0, pitch=45, bearing=-20)
deck = pdk.Deck(layers=[hexagons], initial_view_state=view, map_provider="maplibre",
                map_style=basemap, tooltip={"text": "{elevationValue} trip starts"})
deck.to_html("austin-trip-starts.html")

3D map of Austin with extruded hexagon columns over a topographic basemap, tallest and darkest blue near downtown and the university

to_html() writes a standalone page you can open in any browser. Drag to pan, scroll to zoom, and hold the right mouse button (or Ctrl and drag) to tilt and rotate. Hovering a column shows its count in the tooltip (85 trip starts for the one in the screenshot). Downtown and UT Campus produce 57% of the trip starts (33.3% and 23.7%), and that is where the tallest columns are.

Three things in that call are easy to miss:

  • get_position takes longitude first. Passing ["lat", "lon"] puts your data in the wrong place, usually on the other side of the planet.
  • radius is in meters, and HexagonLayer bins the points in the browser. Change the radius and the columns re-aggregate with no code on your side. elevation_scale multiplies the count into a height in meters.
  • Layer arguments are the deck.gl names in snake case. get_position is deck.gl's getPosition, and radius is radius. The deck.gl layer catalog lists the options for each layer.

How do I set a basemap without a Mapbox token?

pdk.Deck defaults to map_style="dark", one of Carto's hosted basemap styles, and it needs no key. "light", "road", "dark_no_labels" and "light_no_labels" are the other built-in choices. "satellite" needs a Mapbox or Google Maps key (pdk.Deck(map_provider="mapbox", api_keys={"mapbox": "..."}), or the MAPBOX_API_KEY environment variable).

deck = pdk.Deck(layers=[hexagons], initial_view_state=view, map_style="light",
                tooltip={"text": "{elevationValue} trip starts"})
deck.to_html("austin-light.html")

If you want a different tile source, such as the USGS tiles above, there is a catch. map_style accepts a style dictionary only when map_provider="mapbox", so passing one to the MapLibre provider fails with AssertionError: The map_provider parameter must be 'mapbox' when map_style is provided as a dict. The workaround is to give map_style a URL that returns the style JSON. A data:application/json, URL holds the whole style, which is why the Quick Example builds one with quote(json.dumps(usgs)). Keep the attribution text in the style so the credit shows in the map corner, and check a tile provider's terms before you publish a map that uses its tiles.

How do I color points by a column?

A ScatterplotLayer draws one circle per row. Pass expressions as strings and pydeck evaluates them in the browser against each row's columns. Here the red, green and blue channels come from the trip length, with short trips blue and long trips red:

t = (trips["minutes"] / trips["minutes"].quantile(0.95)).clip(0, 1)
trips["r"] = (44 + (215 - 44) * t).astype(int)
trips["g"] = (123 + (48 - 123) * t).astype(int)
trips["b"] = (182 + (39 - 182) * t).astype(int)

points = pdk.Layer(
    "ScatterplotLayer", trips.sample(1500, random_state=0),
    get_position=["start_lon", "start_lat"],
    get_fill_color="[r, g, b, 190]",   # an expression over the columns
    get_radius=45, radius_min_pixels=3,  # meters, but never smaller than 3 pixels
    pickable=True,
)
deck = pdk.Deck(layers=[points], initial_view_state=view, map_provider="maplibre",
                map_style=basemap, tooltip={"text": "{origin} to {dest}: {minutes} min"})
deck.to_html("austin-trip-points.html")

Map of Austin with 1,500 small circles, blue for short trips and red for long ones, clustered around five hubs

get_radius is in meters, so the circles grow and shrink as you zoom. radius_min_pixels=3 keeps them visible when you zoom out. Without it the points shrink to nothing at city scale. The tooltip text uses {column} placeholders that read the hovered row, and it only works for layers with pickable=True.

The color scale here is a plain linear blend. Clipping at the 95th percentile (quantile(0.95), about 33 minutes here) stops a few very long trips from washing out the rest.

How do I draw flows between places?

An ArcLayer connects a source and a target position with a curved line, which suits origin and destination data. Count the trips for each pair first, so the map draws one arc per pair and not one per trip:

flows = (trips[trips["origin"] != trips["dest"]]
         .groupby(["origin", "dest"]).size().rename("trips").reset_index())
flows[["from_lat", "from_lon"]] = hubs.loc[flows["origin"], ["lat", "lon"]].to_numpy()
flows[["to_lat", "to_lon"]] = hubs.loc[flows["dest"], ["lat", "lon"]].to_numpy()

arcs = pdk.Layer(
    "ArcLayer", flows,
    get_source_position=["from_lon", "from_lat"],
    get_target_position=["to_lon", "to_lat"],
    get_width="trips / 45",   # pixels
    get_source_color=[44, 127, 184, 210], get_target_color=[215, 48, 39, 210],
    pickable=True, auto_highlight=True,
)
deck = pdk.Deck(layers=[arcs], initial_view_state=pdk.ViewState(latitude=30.272, longitude=-97.735, zoom=12.6, pitch=35),
                map_provider="maplibre", map_style=basemap,
                tooltip={"text": "{origin} to {dest}: {trips} trips"})
deck.to_html("austin-trip-flows.html")

Map of Austin with curved arcs between five hubs, blue at the start fading to red at the destination, thickest between downtown and the university

Each arc fades from the source color to the target color, so the direction reads without arrowheads. The widest arc runs from UT Campus to Downtown, with 496 trips, and South Congress to Downtown follows with 402 and Downtown to UT Campus with 347. Because each pair has an arc in both directions, the two overlap and look striped. auto_highlight=True brightens the arc under the cursor. A list in deck.layers stacks layers, so you can draw the hexagons and the arcs on one map by passing layers=[hexagons, arcs].

How do I share or embed a pydeck map?

  • A file: deck.to_html("map.html") writes a standalone page. Add iframe_height=600 for Jupyter and open_browser=True to open it right away. Pass css_background_color only if you use no basemap (see the tips below).
  • A notebook: deck.show() (or leaving deck as the last line of a cell) displays the map inline in Jupyter, and deck.update() redraws it after you change a layer's attributes.
  • A Streamlit app: st.pydeck_chart(deck) shows the same Deck. See Charts in Streamlit for the other chart options.
import streamlit as st

st.pydeck_chart(deck)

pydeck vs Folium vs Plotly vs contextily

pydeck Folium Plotly maps contextily
Output Interactive, WebGL Interactive, Leaflet Interactive Static image
3D (columns, tilt) Yes No No No
Many points Tens of thousands to millions A few thousand markers Tens of thousands Any, but static
Aggregation in the browser Hexagons, grids, heatmaps Heatmap plugin Density maps No, aggregate first
Needs WebGL Yes No Yes No
Best for Dense data, flows, exploration Markers, popups, choropleths Dashboards with other Plotly charts Reports and print

For a map in a PDF or on a page that must work everywhere, use contextily with Matplotlib. For an H3 grid you aggregate yourself, the H3 hex map post draws it statically.

Practical Tips

  • css_background_color paints over the basemap. With a map style set, deck.to_html(..., css_background_color="#fff") showed the columns on a white page with no tiles. Leave it out unless you use no basemap.
  • The data is inlined into the HTML. Every row you pass becomes JSON in the page. With all eight columns of the 5,000-row trips table the map file is about 1.25 MB, and with only start_lon and start_lat it is about 520 KB. A million rows would be hundreds of megabytes, so aggregate or sample first.
  • Pass only the columns you use, for example trips[["start_lon", "start_lat"]], to keep the file small.
  • Set the view yourself. pdk.data_utils.compute_view(trips[["start_lon", "start_lat"]]) picks a center and zoom that fits the points, and it is a good starting point before you tune zoom, pitch (tilt, 0 to 60) and bearing (rotation).
  • A blank map usually means WebGL is off, a layer that has the wrong column names, or longitude and latitude swapped. Open the browser console to see the error.

Similar Topics