Hexbin Map in Python

How to make a map with Hexagonal Binning of data in Python with Plotly.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.

Simple Count Hexbin

This page details the use of a figure factory. For more examples with Choropleth maps, see this page.

In [1]:
import plotly.figure_factory as ff
import plotly.express as px

df = px.data.carshare()

fig = ff.create_hexbin_map(
    data_frame=df, lat="centroid_lat", lon="centroid_lon",
    nx_hexagon=10, opacity=0.9, labels={"color": "Point Count"},
)
fig.update_layout(margin=dict(b=0, t=0, l=0, r=0))
fig.show()

Count Hexbin with Minimum Count and Opacity

In [2]:
import plotly.figure_factory as ff
import plotly.express as px

df = px.data.carshare()

fig = ff.create_hexbin_map(
    data_frame=df, lat="centroid_lat", lon="centroid_lon",
    nx_hexagon=10, opacity=0.5, labels={"color": "Point Count"},
    min_count=1,
)
fig.show()

Display the Underlying Data

In [3]:
import plotly.figure_factory as ff
import plotly.express as px

df = px.data.carshare()

fig = ff.create_hexbin_map(
    data_frame=df, lat="centroid_lat", lon="centroid_lon",
    nx_hexagon=10, opacity=0.5, labels={"color": "Point Count"},
    min_count=1, color_continuous_scale="Viridis",
    show_original_data=True,
    original_data_marker=dict(size=4, opacity=0.6, color="deeppink")
)
fig.show()

Compute the Mean Value per Hexbin

In [4]:
import plotly.figure_factory as ff
import plotly.express as px
import numpy as np

df = px.data.carshare()

fig = ff.create_hexbin_map(
    data_frame=df, lat="centroid_lat", lon="centroid_lon",
    nx_hexagon=10, opacity=0.9, labels={"color": "Average Peak Hour"},
    color="peak_hour", agg_func=np.mean, color_continuous_scale="Icefire", range_color=[0,23]
)
fig.show()

Compute the Sum Value per Hexbin

In [5]:
import plotly.figure_factory as ff
import plotly.express as px
import numpy as np

df = px.data.carshare()

fig = ff.create_hexbin_map(
    data_frame=df, lat="centroid_lat", lon="centroid_lon",
    nx_hexagon=10, opacity=0.9, labels={"color": "Summed Car.Hours"},
    color="car_hours", agg_func=np.sum, color_continuous_scale="Magma"
)
fig.show()

Hexbin with Animation

In [6]:
import plotly.figure_factory as ff
import plotly.express as px
import numpy as np

np.random.seed(0)

N = 500
n_frames = 12
lat = np.concatenate([
    np.random.randn(N) * 0.5 + np.cos(i / n_frames * 2 * np.pi) + 10
    for i