@@ -22,7 +22,8 @@ def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict):
22
22
shape_pre2010 = 'gz_2010_us_050_00_500k/gz_2010_us_050_00_500k.shp'
23
23
shape_pre2010 = data_url + shape_pre2010
24
24
df_shape_pre2010 = gp .read_file (shape_pre2010 )
25
- df_shape_pre2010 ['FIPS' ] = df_shape_pre2010 ['STATE' ] + df_shape_pre2010 ['COUNTY' ]
25
+ df_shape_pre2010 ['FIPS' ] = (df_shape_pre2010 ['STATE' ] +
26
+ df_shape_pre2010 ['COUNTY' ])
26
27
df_shape_pre2010 ['FIPS' ] = pd .to_numeric (df_shape_pre2010 ['FIPS' ])
27
28
28
29
states_path = 'cb_2016_us_state_500k/cb_2016_us_state_500k.shp'
@@ -31,6 +32,7 @@ def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict):
31
32
# state df
32
33
df_state = gp .read_file (states_path )
33
34
df_state = df_state [['STATEFP' , 'NAME' , 'geometry' ]]
35
+ df_state = df_state .rename (columns = {'NAME' : 'STATE_NAME' })
34
36
35
37
county_url = 'plotly/package_data/data/cb_2016_us_county_500k/'
36
38
filenames = ['cb_2016_us_county_500k.dbf' ,
@@ -65,9 +67,9 @@ def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict):
65
67
[st_to_state_name_dict ['SD' ], 'SD' ,
66
68
df_shape_pre2010 [df_shape_pre2010 ['FIPS' ] == f ]['geometry' ].iloc [0 ],
67
69
df_shape_pre2010 [df_shape_pre2010 ['FIPS' ] == f ]['FIPS' ].iloc [0 ],
68
- '46' ]
70
+ '46' , 'Shannon' ]
69
71
],
70
- columns = ['State' , 'ST' , 'geometry' , 'FIPS' , 'STATEFP' ],
72
+ columns = ['State' , 'ST' , 'geometry' , 'FIPS' , 'STATEFP' , 'NAME' ],
71
73
index = [max (gdf .index ) + 1 ]
72
74
)
73
75
gdf = gdf .append (singlerow )
@@ -78,9 +80,9 @@ def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict):
78
80
[st_to_state_name_dict ['VA' ], 'VA' ,
79
81
df_shape_pre2010 [df_shape_pre2010 ['FIPS' ] == f ]['geometry' ].iloc [0 ],
80
82
df_shape_pre2010 [df_shape_pre2010 ['FIPS' ] == f ]['FIPS' ].iloc [0 ],
81
- '51' ]
83
+ '51' , 'Bedford City' ]
82
84
],
83
- columns = ['State' , 'ST' , 'geometry' , 'FIPS' , 'STATEFP' ],
85
+ columns = ['State' , 'ST' , 'geometry' , 'FIPS' , 'STATEFP' , 'NAME' ],
84
86
index = [max (gdf .index ) + 1 ]
85
87
)
86
88
gdf = gdf .append (singlerow )
@@ -91,9 +93,9 @@ def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict):
91
93
[st_to_state_name_dict ['AK' ], 'AK' ,
92
94
df_shape_pre2010 [df_shape_pre2010 ['FIPS' ] == f ]['geometry' ].iloc [0 ],
93
95
df_shape_pre2010 [df_shape_pre2010 ['FIPS' ] == f ]['FIPS' ].iloc [0 ],
94
- '02' ]
96
+ '02' , 'Wade Hampton' ]
95
97
],
96
- columns = ['State' , 'ST' , 'geometry' , 'FIPS' , 'STATEFP' ],
98
+ columns = ['State' , 'ST' , 'geometry' , 'FIPS' , 'STATEFP' , 'NAME' ],
97
99
index = [max (gdf .index ) + 1 ]
98
100
)
99
101
gdf = gdf .append (singlerow )
@@ -109,12 +111,14 @@ def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict):
109
111
row_2105 .loc [row_2105 .index [0 ], 'FIPS' ] = 2232
110
112
row_2105 .loc [row_2105 .index [0 ], 'STATEFP' ] = '02'
111
113
gdf = gdf .append (row_2105 )
114
+ gdf = gdf .rename (columns = {'NAME' : 'COUNTY_NAME' })
112
115
113
- gdf_reduced = gdf [['FIPS' , 'STATEFP' , 'geometry' ]]
114
- gdf_statefp = gdf_reduced .merge (df_state [['STATEFP' , 'NAME' ]], on = 'STATEFP' )
116
+ gdf_reduced = gdf [['FIPS' , 'STATEFP' , 'COUNTY_NAME' , 'geometry' ]]
117
+ gdf_statefp = gdf_reduced .merge (df_state [['STATEFP' , 'STATE_NAME' ]],
118
+ on = 'STATEFP' )
115
119
116
120
ST = []
117
- for n in gdf_statefp ['NAME ' ]:
121
+ for n in gdf_statefp ['STATE_NAME ' ]:
118
122
ST .append (state_to_st_dict [n ])
119
123
120
124
gdf_statefp ['ST' ] = ST
@@ -254,7 +258,7 @@ def _human_format(number):
254
258
return '%.2f%s' % (number / k ** magnitude , units [magnitude ])
255
259
256
260
257
- def _intervals_as_labels (array_of_intervals , round_leg , exponent_format ):
261
+ def _intervals_as_labels (array_of_intervals , round_legend_values , exponent_format ):
258
262
"""
259
263
Transform an number interval to a clean string for legend
260
264
@@ -264,7 +268,7 @@ def _intervals_as_labels(array_of_intervals, round_leg, exponent_format):
264
268
string_intervals = []
265
269
for interval in array_of_intervals :
266
270
# round to 2nd decimal place
267
- if round_leg :
271
+ if round_legend_values :
268
272
rnd_interval = [
269
273
(int (interval [i ]) if interval [i ] not in infs else
270
274
interval [i ])
@@ -309,9 +313,12 @@ def _calculations(df, fips, values, index, f, simplify_county, level,
309
313
).exterior .xy [1 ].tolist ()
310
314
311
315
x_c , y_c = fips_polygon_map [f ].centroid .xy
316
+ county_name_str = str (df [df ['FIPS' ] == f ]['COUNTY_NAME' ].iloc [0 ])
317
+ state_name_str = str (df [df ['FIPS' ] == f ]['STATE_NAME' ].iloc [0 ])
312
318
t_c = (
313
- 'County: ' + df [df ['FIPS' ] == f ]['NAME' ].iloc [0 ] + '<br>' +
314
- 'FIPS: ' + str (f ) + '<br> Value: ' + str (values [index ])
319
+ 'County: ' + county_name_str + '<br>' +
320
+ 'State: ' + state_name_str + '<br>' +
321
+ 'FIPS: ' + str (f ) + '<br>Value: ' + str (values [index ])
315
322
)
316
323
317
324
x_centroids .append (x_c [0 ])
@@ -330,8 +337,9 @@ def _calculations(df, fips, values, index, f, simplify_county, level,
330
337
y_c = [poly .centroid .xy [1 ].tolist () for poly in fips_polygon_map [f ]]
331
338
332
339
text = (
333
- 'County: ' + df [df ['FIPS' ] == f ]['NAME' ].iloc [0 ] + '<br>' +
334
- 'FIPS: ' + str (f ) + '<br> Value: ' + str (values [index ])
340
+ 'County: ' + df [df ['FIPS' ] == f ]['COUNTY_NAME' ].iloc [0 ] + '<br>' +
341
+ 'State: ' + df [df ['FIPS' ] == f ]['STATE_NAME' ].iloc [0 ] + '<br>' +
342
+ 'FIPS: ' + str (f ) + '<br>Value: ' + str (values [index ])
335
343
)
336
344
t_c = [text for poly in fips_polygon_map [f ]]
337
345
x_centroids = x_c + x_centroids
@@ -344,12 +352,12 @@ def _calculations(df, fips, values, index, f, simplify_county, level,
344
352
return x_traces , y_traces , x_centroids , y_centroids , centroid_text
345
353
346
354
347
- def create_choropleth (fips , values , scope = ['usa' ], endpts = None ,
355
+ def create_choropleth (fips , values , scope = ['usa' ], binning_endpoints = None ,
348
356
colorscale = None , order = None , simplify_county = 0.02 ,
349
357
simplify_state = 0.02 , asp = None , offline_mode = False ,
350
- show_hover = True , show_statedata = True ,
358
+ show_hover = True , show_state_data = True ,
351
359
state_outline = None , county_outline = None ,
352
- centroid_marker = None , round_leg = False ,
360
+ centroid_marker = None , round_legend_values = False ,
353
361
exponent_format = False , legend_title = '' , df = df ,
354
362
df_state = df_state , ** layout_options ):
355
363
"""
@@ -368,15 +376,15 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
368
376
'United States Virgin Islands'. These must be added manually to the
369
377
list.
370
378
Default = ['usa']
371
- :param (list) endpts : ascending numbers which implicitly define real
372
- number intervals which are used as bins. The colorscale used must have
373
- the same number of colors as the number of bins and this will result
374
- in a categorical colormap.
379
+ :param (list) binning_endpoints : ascending numbers which implicitly define
380
+ real number intervals which are used as bins. The colorscale used must
381
+ have the same number of colors as the number of bins and this will
382
+ result in a categorical colormap.
375
383
:param (list) colorscale: a list of colors with length equal to the
376
384
number of categories of colors. The length must match either all
377
385
unique numbers in the 'values' list or if endpoints is being used, the
378
386
number of categories created by the endpoints.\n
379
- For example, if endpts = [4, 6, 8], then there are 4 bins:
387
+ For example, if binning_endpoints = [4, 6, 8], then there are 4 bins:
380
388
[-inf, 4), [4, 6), [6, 8), [8, inf)
381
389
:param (list) order: a list of the unique categories (numbers/bins) in any
382
390
desired order. This is helpful if you want to order string values to
@@ -400,7 +408,7 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
400
408
yet part of the plotly.py python library. Stay tuned for updates.
401
409
Default = False
402
410
:param (bool) show_hover: show county hover and centroid info
403
- :param (bool) show_statedata : reveals state boundary lines
411
+ :param (bool) show_state_data : reveals state boundary lines
404
412
:param (dict) state_outline: dict of attributes of the state outline
405
413
including width and color. See
406
414
https://plot.ly/python/reference/#scatter-marker-line for all valid
@@ -412,8 +420,8 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
412
420
:param (dict) centroid_marker: dict of attributes of the centroid marker.
413
421
See https://plot.ly/python/reference/#scatter-marker for all valid
414
422
params
415
- :param (bool) round_leg : automatically round the numbers that appear in
416
- the legend to the nearest integer.
423
+ :param (bool) round_legend_values : automatically round the numbers that
424
+ appear in the legend to the nearest integer.
417
425
Default = False
418
426
:param (bool) exponent_format: if set to True, puts numbers in the K, M,
419
427
B number format. For example 4000.0 becomes 4.0K
@@ -438,15 +446,16 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
438
446
values = df_sample_r['TOT_POP'].tolist()
439
447
fips = df_sample_r['FIPS'].tolist()
440
448
441
- endpts = list(np.mgrid[min(values):max(values):4j])
449
+ binning_endpoints = list(np.mgrid[min(values):max(values):4j])
442
450
colorscale = ["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0",
443
451
"#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"]
444
452
fig = ff.create_choropleth(
445
- fips=fips, values=values, scope=['Florida'], show_statedata =True,
446
- colorscale=colorscale, endpts=endpts, round_leg=True ,
447
- plot_bgcolor='rgb(229,229,229)', paper_bgcolor ='rgb(229,229,229)',
448
- legend_title='Florida Population', exponent_format=True ,
453
+ fips=fips, values=values, scope=['Florida'], show_state_data =True,
454
+ colorscale=colorscale, binning_endpoints=binning_endpoints ,
455
+ round_legend_values=True, plot_bgcolor ='rgb(229,229,229)',
456
+ paper_bgcolor='rgb(229,229,229)', legend_title='Florida Population',
449
457
county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
458
+ exponent_format=True,
450
459
)
451
460
py.iplot(fig, filename='choropleth_florida')
452
461
```
@@ -473,7 +482,7 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
473
482
values = df_sample_r['TOT_POP'].tolist()
474
483
fips = df_sample_r['FIPS'].tolist()
475
484
fig = ff.create_choropleth(
476
- fips=fips, values=values, scope=NE_states, show_statedata =True
485
+ fips=fips, values=values, scope=NE_states, show_state_data =True
477
486
)
478
487
py.iplot(fig, filename='choropleth_new_england')
479
488
```
@@ -505,7 +514,7 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
505
514
fig = ff.create_choropleth(
506
515
fips=fips, values=values, colorscale=colorscale,
507
516
scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'],
508
- endpts =[14348, 63983, 134827, 426762, 2081313],
517
+ binning_endpoints =[14348, 63983, 134827, 426762, 2081313],
509
518
county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
510
519
legend_title='California Counties',
511
520
title='California and Nearby States'
@@ -534,15 +543,16 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
534
543
df_sample['State FIPS Code'] + df_sample['County FIPS Code']
535
544
)
536
545
537
- endpts = list(np.linspace(1, 12, len(colorscale) - 1))
538
- colorscale = ["#f7fbff","#ebf3fb","#deebf7","#d2e3f3","#c6dbef","#b3d2e9",
539
- "#9ecae1", "#85bcdb","#6baed6","#57a0ce","#4292c6","#3082be",
540
- "#2171b5","#1361a9", "#08519c","#0b4083","#08306b"]
546
+ binning_endpoints = list(np.linspace(1, 12, len(colorscale) - 1))
547
+ colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef",
548
+ "#b3d2e9", "#9ecae1", "#85bcdb", "#6baed6", "#57a0ce",
549
+ "#4292c6", "#3082be", "#2171b5", "#1361a9", "#08519c",
550
+ "#0b4083","#08306b"]
541
551
fips = df_sample['FIPS']
542
552
values = df_sample['Unemployment Rate (%)']
543
553
fig = ff.create_choropleth(
544
554
fips=fips, values=values, scope=['usa'],
545
- endpts=endpts , colorscale=colorscale,
555
+ binning_endpoints=binning_endpoints , colorscale=colorscale,
546
556
show_hover=True, centroid_marker={'opacity': 0},
547
557
asp=2.9, title='USA by Unemployment %',
548
558
legend_title='Unemployment %'
@@ -581,9 +591,10 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
581
591
# make fips numeric
582
592
fips = map (lambda x : int (x ), fips )
583
593
584
- if endpts :
585
- intervals = utils .endpts_to_intervals (endpts )
586
- LEVELS = _intervals_as_labels (intervals , round_leg , exponent_format )
594
+ if binning_endpoints :
595
+ intervals = utils .endpts_to_intervals (b
10000
inning_endpoints )
596
+ LEVELS = _intervals_as_labels (intervals , round_legend_values ,
597
+ exponent_format )
587
598
else :
588
599
if not order :
589
600
LEVELS = sorted (list (set (values )))
@@ -646,8 +657,8 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
646
657
raise exceptions .PlotlyError (
647
658
"You have {} LEVELS. Your number of colors in 'colorscale' must "
648
659
"be at least the number of LEVELS: {}. If you are "
649
- "using 'endpts ' then 'colorscale' must have at "
650
- "least len(endpts ) + 2 colors" .format (
660
+ "using 'binning_endpoints ' then 'colorscale' must have at "
661
+ "least len(binning_endpoints ) + 2 colors" .format (
651
662
len (LEVELS ), min (LEVELS , LEVELS [:20 ])
652
663
)
653
664
)
@@ -668,7 +679,7 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
668
679
'American Samoa' ]
669
680
for state in scope :
670
681
if state .lower () == 'usa' :
671
- scope_names = df ['NAME ' ].unique ()
682
+ scope_names = df ['STATE_NAME ' ].unique ()
672
683
scope_names = list (scope_names )
673
684
for ex_st in extra_states :
674
685
try :
@@ -679,14 +690,14 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
679
690
if state in st_to_state_name_dict .keys ():
680
691
state = st_to_state_name_dict [state ]
681
692
scope_names .append (state )
682
- df_state = df_state [df_state ['NAME ' ].isin (scope_names )]
693
+ df_state = df_state [df_state ['STATE_NAME ' ].isin (scope_names )]
683
694
684
695
plot_data = []
685
696
x_centroids = []
686
697
y_centroids = []
687
698
centroid_text = []
688
699
fips_not_in_shapefile = []
689
- if not endpts :
700
+ if not binning_endpoints :
690
701
for index , f in enumerate (fips ):
691
702
level = values [index ]
692
703
try :
@@ -695,7 +706,8 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
695
706
(x_traces , y_traces , x_centroids ,
696
707
y_centroids , centroid_text ) = _calculations (
57AE
697
708
df , fips , values , index , f , simplify_county , level ,
698
- x_centroids , y_centroids , centroid_text , x_traces , y_traces
709
+ x_centroids , y_centroids , centroid_text , x_traces ,
710
+ y_traces
699
711
)
700
712
except KeyError :
701
713
fips_not_in_shapefile .append (f )
@@ -713,7 +725,8 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
713
725
(x_traces , y_traces , x_centroids ,
714
726
y_centroids , centroid_text ) = _calculations (
715
727
df , fips , values , index , f , simplify_county , level ,
716
- x_centroids , y_centroids , centroid_text , x_traces , y_traces
728
+ x_centroids , y_centroids , centroid_text , x_traces ,
729
+ y_traces
717
730
)
718
731
except KeyError :
719
732
fips_not_in_shapefile .append (f )
@@ -790,7 +803,7 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
790
803
hover_points .update (centroids_on_select )
791
804
plot_data .append (hover_points )
792
805
793
- if show_statedata :
806
+ if show_state_data :
794
807
state_data = dict (
795
808
type = 'scatter' ,
796
809
legendgroup = 'States' ,
@@ -880,7 +893,9 @@ def create_choropleth(fips, values, scope=['usa'], endpts=None,
880
893
881
894
# aspect ratio
882
895
if asp is None :
883
- asp = (USA_XRANGE [1 ] - USA_XRANGE [0 ]) / (USA_YRANGE [1 ] - USA_YRANGE [0 ])
896
+ usa_x_range = USA_XRANGE [1 ] - USA_XRANGE [0 ]
897
+ usa_y_range = USA_YRANGE [1 ] - USA_YRANGE [0 ]
898
+ asp = usa_x_range / usa_y_range
884
899
885
900
# based on your figure
886
901
width = float (fig ['layout' ]['xaxis' ]['range' ][1 ] -
0 commit comments