Mapboxgl Python Library for location data visualization

https://github.com/mapbox/mapboxgl-jupyter

Requirements

These examples require the installation of the following python modules

pip install mapboxgl
pip install pandas
In [ ]:
import json
import pandas as pd
import os
from mapboxgl.utils import *
from mapboxgl.viz import *
In [ ]:
# Load data from sample csv
data_url = 'https://raw.githubusercontent.com/mapbox/mapboxgl-jupyter/master/examples/data/points.csv'
df = pd.read_csv(data_url).round(3)
df.head(2)

Set your Mapbox access token.

Set a MAPBOX_ACCESS_TOKEN environment variable or copy/paste your token
If you do not have a Mapbox access token, sign up for an account at https://www.mapbox.com/
If you already have an account, you can grab your token at https://www.mapbox.com/account/

In [ ]:
# Must be a public token, starting with `pk`
token = os.getenv('MAPBOX_ACCESS_TOKEN')

Create a visualization from a Pandas dataframe

In [ ]:
# Create a geojson Feature Collection from the current dataframe
# optionally create a geojson file export by including the argument 
# filename='../data/healthcare_points.geojson',
geodata = df_to_geojson(df, 
              properties=['Avg Medicare Payments', 'Avg Covered Charges', 'date'], 
              lat='lat', 
              lon='lon', 
              precision=3)
In [ ]:
# Just show a map of the data
viz = CircleViz(geodata, 
                access_token=token, 
                radius=2, 
                center=(-95, 40), 
                zoom=3)
viz.show()

Add data-driven styles and a legend to the viz

In [ ]:
# Generate data breaks using numpy quantiles and color stops from colorBrewer
measure = 'Avg Medicare Payments'
color_breaks = [round(df[measure].quantile(q=x*0.1), 2) for x in range(1, 9)]
color_stops = create_color_stops(color_breaks, colors='YlGnBu')

# Create the viz from the dataframe
viz = CircleViz(geodata,
                access_token=token, 
                color_property="Avg Medicare Payments",
                color_stops=color_stops,
                radius=2.5,
                stroke_color='black',
                stroke_width=0.2,
                center=(-95, 40),
                zoom=3,
                below_layer='waterway-label')
viz.show()

Add a scale bar to the viz

In [ ]:
viz.scale = True
viz.scale_unit_system = 'imperial'
viz.show()

Add labels to the viz

In [ ]:
viz.label_property = "Avg Medicare Payments"
viz.stroke_width = 0
viz.label_size = 8
viz.legend_text_numeric_precision = 2
viz.show()

Change viz data property and color scale

In [ ]:
# Generate a new data domain breaks and a new color palette from colorBrewer2
measure = 'Avg Covered Charges'
color_breaks = [round(df[measure].quantile(q=x*0.1), 1) for x in range(1, 9)]
color_stops = create_color_stops(color_breaks, colors='YlOrRd')

# Show the viz
viz.color_property = 'Avg Covered Charges'
viz.color_stops = color_stops
viz.show()

Change the viz map style

In [ ]:
# Map settings
viz.style = 'mapbox://styles/mapbox/dark-v9?optimize=true'
viz.label_color = 'hsl(0, 0%, 70%)'
viz.label_halo_color = 'hsla(0, 0%, 10%, 0.75)'

# Legend settings
viz.legend_gradient = False
viz.legend_fill = '#343332'
viz.legend_header_fill = '#343332'
viz.legend_text_color = 'hsl(0, 0%, 70%)'
viz.legend_key_borders_on = False
viz.legend_title_halo_color = 'hsla(0, 0%, 10%, 0.75)'

# Scale bar settings
viz.scale = True
viz.scale_border_color = 'hsla(0, 0%, 10%, 0.75)'
viz.scale_position = 'bottom-left'
viz.scale_background_color = '#343332'
viz.scale_text_color = 'hsl(0, 0%, 70%)'

# Render map
viz.show()

Create a graduated cricle viz based on two data properties

In [ ]:
# Generate data breaks and color stops from colorBrewer
measure_color = 'Avg Covered Charges'
color_breaks = [round(df[measure_color].quantile(q=x*0.1), 2) for x in range(2, 10)]
color_stops = create_color_stops(color_breaks, colors='Blues')

# Generate radius breaks from data domain and circle-radius range
measure_radius = 'Avg Medicare Payments'
radius_breaks = [round(df[measure_radius].quantile(q=x*0.1), 2) for x in range(2, 10)]
radius_stops = create_radius_stops(radius_breaks, 0.5, 10)

# Create the viz
viz2 = GraduatedCircleViz(geodata, 
                          access_token=token,
                          color_property="Avg Covered Charges",
                          color_stops=color_stops,
                          radius_property="Avg Medicare Payments",
                          radius_stops=radius_stops,
                          stroke_color='black',
                          stroke_width=0.5,
                          center=(-95, 40),
                          zoom=3,
                          opacity=0.75,
                          below_layer='waterway-label')
viz2.show()

Create a heatmap viz

In [ ]:
measure = 'Avg Medicare Payments'
heatmap_color_stops = create_color_stops([0.01, 0.25, 0.5, 0.75, 1], colors='RdPu')
heatmap_radius_stops = [[0, 3], [14, 100]] # increase radius with zoom

color_breaks = [round(df[measure].quantile(q=x*0.1), 2) for x in range(2, 10)]
color_stops = create_color_stops(color_breaks, colors='Spectral')

heatmap_weight_stops = create_weight_stops(color_breaks)

# Create the heatmap 
viz3 = HeatmapViz(geodata, 
                  access_token=token,
                  weight_property="Avg Medicare Payments",
                  weight_stops=heatmap_weight_stops,
                  color_stops=heatmap_color_stops,
                  radius_stops=heatmap_radius_stops,
                  opacity=0.8,
                  center=(-95, 40),
                  zoom=3,
                  below_layer='waterway-label')
viz3.show()

Create a clustered circle map

In [ ]:
# Create a clustered circle map
color_stops = create_color_stops([1, 10, 25, 50, 75, 100], colors='YlOrBr')

viz4 = ClusteredCircleViz(geodata, 
                          access_token=token,
                          color_stops=color_stops,
                          stroke_color='black',
                          radius_stops=[[1, 5], [10, 10], [50, 15], [100, 20]],
                          radius_default=2,
                          cluster_maxzoom=10,
                          cluster_radius=30,
                          label_size=12,
                          opacity=0.9,
                          center=(-95, 40),
                          zoom=3)
viz4.show()

Save our viz to an HTML file for distribution

Note

Viz export contains a reference to the data in this visualization. Serve data from the same directory as the HTML file to vis your visualization.

In [ ]:
with open('viz4.html', 'w') as f:
    f.write(viz4.create_html())

Run exported HTML example

Python2: python -m SimpleHTTPServer 8080

Python3: python3 -m http.server 8080

Now navigate your browser to http://localhost:8080/viz4.html to see the viz

Download the map canvas to a PNG file

Note

Screen captures of the map and legend are separate; additional image processing is required to export a map with visible legend and other Mapbox control elements. Click either the Map or Legend links to download the corresponding PNG file.

In [ ]:
viz4.add_snapshot_links = True
viz4.show()