forked from ConnectedSystems/Dash-Choropleth-Example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
choropleth_example.py
171 lines (141 loc) · 4.54 KB
/
choropleth_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# -*- coding: utf-8 -*-
"""
Choropleth example with Dash
Example using data on Limited English Proficiency in Portland.
Shapefile taken from:
https://gis-pdx.opendata.arcgis.com/datasets/a0e5ed95749d4181abfb2a7a2c98d7ef_121
Note that there is currently a bug in dash which breaks interactions after second layer change.
See https://github.com/plotly/dash/issues/223 for more info.
"""
import json
import dash
import dash_core_components as dcc
import dash_html_components as html
import geopandas as gpd
import randomcolor
mapbox_key = None
if not mapbox_key:
raise RuntimeError("Mapbox key not specified! Edit this file and add it.")
# Example shapefile from:
# https://gis-pdx.opendata.arcgis.com/datasets/a0e5ed95749d4181abfb2a7a2c98d7ef_121
# Portland Limited English Proficiency
lep_shp = 'data/lep/Limited_English_Proficiency.shp'
lep_df = gpd.read_file(lep_shp)
# Generate centroids for each polygon to use as marker locations
lep_df['lon_lat'] = lep_df['geometry'].apply(lambda row: row.centroid)
lep_df['LON'] = lep_df['lon_lat'].apply(lambda row: row.x)
lep_df['LAT'] = lep_df['lon_lat'].apply(lambda row: row.y)
lep_df = lep_df.drop('lon_lat', axis=1)
lon = lep_df['LON'][0]
lat = lep_df['LAT'][0]
# Get list of languages given in the shapefile
langs = [lng for lng in lep_df.columns
if lng.istitle() and
lng not in ['Id', 'Id2', 'Total_Pop_'] and
'Shape' not in lng]
# Generate stats for example
lep_df['NUM_LEP'] = lep_df[langs].sum(axis=1)
# Create hover info text
lep_df['HOVER'] = 'Geography: ' + lep_df.Geography + \
'<br /> Num. LEP:' + lep_df.NUM_LEP.astype(str)
# Create overlay data for each language option
overlay_data = {
lng.lower(): json.loads(lep_df.loc[lep_df[lng] > 0, :].to_json())
for lng in langs
}
# Generate colors for each language
seed_val = 10 # Set a seed value to generate the same colors between runs
color_generator = randomcolor.RandomColor(seed=seed_val)
colors = color_generator.generate(count=len(langs))
# Setup overlay colors (one for each layer)
overlay_color = {
lng.lower(): shade
for lng, shade in zip(langs, colors)
}
# Create layer options that get displayed to the user in the dropdown
all_opt = {'label': 'All', 'value': 'all'}
opts = [{'label': lng.title(), 'value': lng.lower()} for lng in langs]
opts.append(all_opt)
# template for map
map_layout = {
'title': 'Portland LEP',
'data': [{
'lon': lep_df['LON'],
'lat': lep_df['LAT'],
'mode': 'markers',
'marker': {
'opacity': 0.0,
},
'type': 'scattermapbox',
'name': 'Portland LEP',
'text': lep_df['HOVER'],
'hoverinfo': 'text',
'showlegend': True,
}],
'layout': {
'autosize': True,
'hovermode': 'closest',
'margin': {'l': 0, 'r': 0, 'b': 0, 't': 0},
'mapbox': {
'accesstoken': mapbox_key,
'center': {
'lat': lat,
'lon': lon
},
'zoom': 8.0,
'bearing': 0.0,
'pitch': 0.0,
},
}
}
app = dash.Dash()
app.layout = html.Div([
html.H1(children='Portland - Limited English Proficiency (Choropleth Example)'),
dcc.Dropdown(
id='overlay-choice',
options=opts,
value='all'
),
html.Div([
dcc.Graph(id='map-display'),
])
])
@app.callback(
dash.dependencies.Output('map-display', 'figure'),
[dash.dependencies.Input('overlay-choice', 'value')])
def update_map(overlay_choice):
if overlay_choice == 'all':
layers = []
for overlay in overlay_data:
if overlay == 'all':
continue
# End if
layers.append({
'name': overlay,
'source': overlay_data[overlay],
'sourcetype': 'geojson',
'type': 'fill',
'opacity': 0.3,
'color': overlay_color[overlay]
})
# End for
else:
chosen_dataset = overlay_data.get(overlay_choice, None)
if overlay_data is None:
raise RuntimeError("Invalid overlay option")
# End if
layers = [{
'name': overlay_choice,
'source': chosen_dataset,
'sourcetype': 'geojson',
'type': 'fill',
'opacity': 1.0,
'color': overlay_color[overlay_choice]
}]
# End if
tmp = map_layout
tmp['layout']['mapbox']['layers'] = layers
return tmp
# End update_map()
if __name__ == '__main__':
app.run_server(debug=True, port=8051)