Show Sidebar Hide Sidebar

Mapbox Density Heatmap in Python

How to make a Mapbox Density Heatmap in Python with Plotly.

Mapbox Access Token

To plot on Mapbox maps with Plotly you may need a Mapbox account and a public Mapbox Access Token. See our Mapbox Map Layers documentation for more information.

Stamen Terrain base map (no token needed): density mapbox with plotly.express

Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on "tidy" data.

With px.density_mapbox, each row of the DataFrame is represented as a point smoothed with a given radius of influence.

In [1]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv')

import plotly.express as px
fig = px.density_mapbox(df, lat='Latitude', lon='Longitude', z='Magnitude', radius=10,
                        center=dict(lat=0, lon=180), zoom=0,
                        mapbox_style="stamen-terrain")
fig.show()

Stamen Terrain base map (no token needed): density mapbox with plotly.graph_objects

If Plotly Express does not provide a good starting point, it is also possible to use the more generic go.Densitymapbox function from plotly.graph_objects.

In [2]:
import pandas as pd
quakes = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv')

import plotly.graph_objects as go
fig = go.Figure(go.Densitymapbox(lat=quakes.Latitude, lon=quakes.Longitude, z=quakes.Magnitude, 
                                 radius=10))
fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()