Skip to content

Commit

Permalink
Merge 6697cbc into e5346c0
Browse files Browse the repository at this point in the history
  • Loading branch information
akacarlyann committed Feb 27, 2018
2 parents e5346c0 + 6697cbc commit 749d5d0
Show file tree
Hide file tree
Showing 6 changed files with 395 additions and 0 deletions.
64 changes: 64 additions & 0 deletions docs-markdown/viz.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,67 @@ viz = HeatmapViz('points.geojson',
viz.show()
```
![screen shot 2018-02-21 at 3 34 55 pm](https://user-images.githubusercontent.com/11286381/36511775-cfc4d794-171c-11e8-86b9-5f1a6060a387.png)


## class ChloroplethViz

The `ChloroplethViz` object handles the creation of a chloropleth map and is built on top of the `MapViz` class.

### Params
**ChloroplethViz**(_data, label_property=None, color_property=None, color_stops=None, color_default='grey', color_function_type='interpolate', line_color='white', line_stroke='solid', line_width=1, *args, **kwargs_)

Parameter | Description | Example
--|--|--
data | name of GeoJson file or object
label_property | property to use for marker label | "density"
color_property | property to determine circle color | "density"
color_stops | property to determine circle color | [[0, "red"], [0.5, "blue"], [1, "green"]]
color_default | property to determine default circle color if match lookup fails | "#F0F0F0"
color_function_type | property to determine `type` used by Mapbox to assign color | "interpolate"
line_color | property to determine chloropleth line color | "#FFFFFF"
line_stroke | property to determine chloropleth line stroke (one of solid, dashed, dotted, dash dot) | "solid"
line_width | property to determine chloropleth line width | 1

[View options](https://github.com/mapbox/mapboxgl-jupyter/blob/master/docs-markdown/viz.md#params)

### Usage
```python
import os
from mapboxgl.utils import *
from mapboxgl.viz import *

# Load data from sample geojson features
with open('us-states.geojson', 'r') as f:
data = json.load(f)

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

# Color stops
color_stops = [
[0.0, 'rgb(255,255,204)'],
[100.0, 'rgb(255,237,160)'],
[500.0, 'rgb(253,141,60)'],
[2000.0, 'rgb(227,26,28)'],
[5000.0, 'rgb(189,0,38)'],
[10000.0,'rgb(128,0,38)']
]

# Create Chloropleth
viz = ChloroplethViz(data,
access_token=token,
color_property='density',
color_stops=sample_color_stops,
color_function_type='interpolate',
default_color='#bada55',
line_stroke='dashed',
line_color='rgb(128,0,38)',
line_width=1,
opacity=0.8,
center=(-96, 37.8),
zoom=3,
below_layer='waterway-label
)
viz.show()
```
![screen shot 2018-02-26 at 4 54 59 pm](https://user-images.githubusercontent.com/13527707/36704653-186bb2e0-1b16-11e8-9dac-2d929e678be9.png)
127 changes: 127 additions & 0 deletions examples/chloropleth-viz-example.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Mapboxgl Python Library\n",
"\n",
"https://github.com/mapbox/mapboxgl-jupyter"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import sys\n",
"import os\n",
"\n",
"from mapboxgl.viz import *\n",
"from mapboxgl.utils import *\n",
"from mapboxgl.colors import *\n",
"\n",
"# Must be a public token, starting with `pk`\n",
"token = os.getenv('MAPBOX_ACCESS_TOKEN')\n",
"\n",
"# load geojson features\n",
"with open('us-states.geojson', 'r') as f:\n",
" data = json.load(f)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Chloropleths with interpolated color assignment"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sample_color_stops = [\n",
" [0.0, 'rgb(255,255,204)'],\n",
" [100.0, 'rgb(255,237,160)'],\n",
" [500.0, 'rgb(253,141,60)'],\n",
" [2000.0, 'rgb(227,26,28)'],\n",
" [5000.0, 'rgb(189,0,38)'],\n",
" [10000.0,'rgb(128,0,38)']\n",
"]\n",
" \n",
"viz = ChloroplethViz(data, opacity=0.8)\n",
"viz.color_property = 'density'\n",
"viz.color_stops = sample_color_stops\n",
"viz.color_function_type = 'interpolate'\n",
"viz.default_color = '#bada55'\n",
"viz.line_stroke = 'dashed'\n",
"viz.line_color = 'rgb(128,0,38)'\n",
"viz.line_width = 1\n",
"viz.center = (-96, 37.8)\n",
"viz.zoom = 3\n",
"viz.below_layer = 'waterway-label'\n",
"viz.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Chloropleths with match-type color scheme"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"match_color_stops = [\n",
" ['Massachusetts', 'rgb(46,204,113)'],\n",
" ['Utah', 'rgb(231,76,60)'],\n",
" ['California', 'rgb(142,68,173)'],\n",
"]\n",
" \n",
"viz = ChloroplethViz(data, opacity=0.8)\n",
"viz.color_property = 'name'\n",
"viz.color_stops = match_color_stops\n",
"viz.color_function_type = 'match'\n",
"viz.color_default = 'rgba(52,73,94,0.5)'\n",
"viz.center = (-96, 37.8)\n",
"viz.zoom = 3\n",
"viz.below_layer = 'waterway-label'\n",
"viz.show()"
]
}
],
"metadata": {
"anaconda-cloud": {
"attach-environment": true,
"environment": "Root",
"summary": "Mapboxgl Python Data Visualization example"
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
1 change: 1 addition & 0 deletions examples/us-states.geojson

Large diffs are not rendered by default.

133 changes: 133 additions & 0 deletions mapboxgl/templates/chloropleth.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
{% extends "main.html" %}

<!-- update legend item key style -->
{% block extra_css %}
<style type='text/css'>
.legend div span { border-radius: 20%; }
</style>
{% endblock extra_css %}

{% block javascript %}
var legend = document.getElementById('legend');

mapboxgl.accessToken = '{{ accessToken }}';

var map = new mapboxgl.Map({
container: 'map',
style: '{{ styleUrl }}',
center: {{ center }},
zoom: {{ zoom }},
transformRequest: (url, resourceType)=> {
if ( url.slice(0,22) == 'https://api.mapbox.com' ) {
//Add Python Plugin identifier for Mapbox API traffic
return {
url: [url.slice(0, url.indexOf("?")+1), "pluginName=PythonMapboxgl&", url.slice(url.indexOf("?")+1)].join('')
}
}
else {
//Do not transform URL for non Mapbox GET requests
return {url: url}
}
}
});

map.addControl(new mapboxgl.NavigationControl());

calcCircleColorLegend({{ colorStops }}, "{{ colorProperty }}");

map.on('style.load', function() {

// Add geojson data source
map.addSource("data", {
"type": "geojson",
"data": {{ geojson_data }},
"buffer": 1,
"maxzoom": 14
});

// Add data layer
map.addLayer({
"id": "chloropleth-fill",
"source": "data",
"type": "fill",
"paint": {
"fill-color": generatePropertyExpression("{{ colorType }}", "{{ colorProperty }}", {{ colorStops }}, "{{ defaultColor }}"),
"fill-opacity": {{ opacity }}
}
}, "{{ belowLayer }}" );

// Add data layer
map.addLayer({
"id": "chloropleth-line",
"source": "data",
"type": "line",
"layout": {
"line-join": "round",
"line-cap": "round"
},
"paint": {
{% if lineDashArray %}
"line-dasharray": {{ lineDashArray }},
{% endif %}
"line-color": "{{ lineColor }}",
"line-width": {{ lineWidth }},
"line-opacity": {{ opacity }}
}
}, "{{ belowLayer }}" );

// Add label layer
map.addLayer({
"id": "chloropleth-label",
"source": "data",
"type": "symbol",
"layout": {
{% if labelProperty %}
"text-field": "{{ labelProperty }}",
{% endif %}
"text-size" : generateInterpolateExpression('zoom', [[0,8],[22,16]] ),
"text-offset": [0,-1]
},
"paint": {
"text-halo-color": "white",
"text-halo-width": 1
}
}, "{{belowLayer}}" );

// Create a popup
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});

// Show the popup on mouseover
map.on('mousemove', 'chloropleth-fill', function(e) {
map.getCanvas().style.cursor = 'pointer';

let f = e.features[0];
let popup_html = '<div>';

for (key in f.properties) {
popup_html += '<li><b> ' + key + '</b>: ' + f.properties[key] + ' </li>'
}

popup_html += '</div>'
popup.setLngLat(e.lngLat)
.setHTML(popup_html)
.addTo(map);
});

map.on('mouseleave', 'chloropleth-fill', function() {
map.getCanvas().style.cursor = '';
popup.remove();
});

// Fly to on click
map.on('click', 'chloropleth-fill', function(e) {
map.flyTo({
center: e.lngLat,
zoom: map.getZoom() + 1
});
});

});
{% endblock %}
1 change: 1 addition & 0 deletions mapboxgl/templates/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
width: 10px;
}
</style>
{% block extra_css %}{% endblock extra_css %}
</head>
<body>

Expand Down
Loading

0 comments on commit 749d5d0

Please sign in to comment.