mapbox / mapboxgl-jupyter

Use Mapbox GL JS to visualize data in a Python Jupyter notebook
MIT License
668 stars 137 forks source link

Function types identity, step #161

Open akacarlyann opened 5 years ago

akacarlyann commented 5 years ago

Adds support for 'identity' and 'step' expression types for color_function_type, radius_function_type or height_function_type. Closes #144 and #169.

akacarlyann commented 5 years ago

@ryanbaumann this seemed pretty similar to adding the 'step' expression mentioned in #169, so I've folded that in here along with some changes to the JS legend functions and viz.py. Added some tests and docs.

Here's an example I've been using to test this out:

import pandas as pd
import os
from mapboxgl.utils import *
from mapboxgl.viz import *

# 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)

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

# Create a geojson Feature Collection from the current dataframe
df.loc[df['Avg Medicare Payments'] >= 6000, 'color'] = 'yellow'
df.loc[df['Avg Medicare Payments'] >= 9000, 'color'] = 'red'
df['color'].fillna('blue', inplace=True)

df['Avg Medicare Payments'] = df['Avg Medicare Payments'] #.round(-3)
geodata = df_to_geojson(df, 
                        properties=['Avg Medicare Payments', 
                                    'Avg Covered Charges', 
                                    'date', 'Provider Id', 'color'], 
                        lat='lat', 
                        lon='lon', 
                        precision=3)

# Generate data breaks using numpy quantiles and color stops from colorBrewer
measure = 'Avg Medicare Payments'
color_breaks = [round(df[measure].quantile(q=x*0.01), 0) for x in range(0, 100, 25)]
color_stops = create_color_stops(color_breaks, colors='YlGnBu')

# Create the viz from the dataframe
viz = CircleViz(geodata,
                access_token=token, 
                color_property=measure,
                color_function_type='step', 
                legend=True,
                color_default='whitesmoke',
                color_stops=color_stops,
                radius=2.5,
                stroke_color='black',
                #legend_layout='horizontal',
                #legend_key_shape='bar',
                stroke_width=0.2,
                center=(-95, 40),
                zoom=3,
                below_layer='waterway-label',
                height='300px')
viz.show()

# viz.color_property='color'
# viz.color_function_type='identity'
# viz.show()