-
Notifications
You must be signed in to change notification settings - Fork 0
/
covid.py
2071 lines (1721 loc) · 78.9 KB
/
covid.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 20:57:44 2020
@author: Matt Bayer
"""
import datetime
import dateutil.parser
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import urllib
import os
import re
import plotly
import plotly.subplots
import plotly.express as px
import plotly.graph_objects as go
import json
import tableauscraper
def plotly_colorbubble(
geodata,
sizecol,
colorcol,
popcol='Population',
size_factor=1,
color_range=[0, 600],
colorscale=None,
location_names=None,
plotlabels=None,
savefile='.\\temp.html',
fig_height='100%',
showfig = True,
):
"""Create interactive plotly map figure, with bubbles that show size and color
geodata -- GeoPandas DataFrame
sizecol -- Column to use for bubble sizes
colorcol -- Column to use for bubble color
fig_height -- html tag for height of the figure. Default is to fill the div; could also specify pixels.
showfig -- flag for displaying the figure after it is created
"""
# Input process plotlabels
plotlabels_default = dict(title='Color-Bubble Map',
sizelabel=sizecol,
colorlabel=colorcol,
sizelegend=sizecol,
colorlegend=colorcol,
)
if plotlabels is not None:
# replace default values with the passed values
for n in plotlabels.keys():
plotlabels_default[n] = plotlabels[n]
# then overwrite
plotlabels = plotlabels_default
# Colors for the background map (not used) and marker lines
line_colors = {'land':'lightgray', 'border':'darkgray', 'marker':'dimgray'}
# Background map
fig = plotly_backmap(geodata)
fig.update_layout(title=plotlabels['title'])
# Get latitude and longitude of centroids for plotting the bubbles,
# if not already set.
# This will give warning but I don't care
if 'plotlon' not in geodata.columns:
geodata['plotlon'] = geodata.geometry.centroid.x
if 'plotlat' not in geodata.columns:
geodata['plotlat'] = geodata.geometry.centroid.y
# Create display names for tooltip
if location_names is None:
location_names = geodata.index
# Set any values < 0 to 0
geodata[sizecol] = geodata[sizecol].apply(lambda x: max(x,0))
# Create the bubble figure
fig.add_trace(
go.Scattergeo(
lon=geodata.plotlon,
lat=geodata.plotlat,
text=location_names,
customdata=geodata[popcol],
marker=dict(
size=geodata[sizecol],
sizeref=size_factor,
sizemode='area',
color=geodata[colorcol],
cmin=color_range[0],
cmax=color_range[1],
colorscale=colorscale,
colorbar=dict(
title=plotlabels['colorlabel'],
yanchor='bottom',
y=0.6,
len=0.25,
thickness=12,
),
),
line=dict(color=line_colors['marker']),
hovertemplate=
'<b>%{text}</b><br>' +
'Population: %{customdata:.0f}<br>' +
plotlabels['sizelabel'] + ' : %{marker.size:.1f}<br>' +
plotlabels['colorlabel'] + ' : %{marker.color:.1f}'+
'<extra></extra>',
name=sizecol,
showlegend=False,
legendgroup=sizecol,
)
)
# Add bubble legend (using dummy traces)
# find dummy locations - put outside the map and hide with a white circle
lon_range = np.abs(geodata.plotlon.max() - geodata.plotlon.min())
idx = geodata.plotlon.idxmax()
dummy_lon = geodata.plotlon[idx] + 0.1*lon_range
dummy_lat = geodata.plotlat[idx]
# Bubble legend
plotly_add_bubblelegend(
fig,
sizeref=size_factor,
dummy_lon=dummy_lon,
dummy_lat=dummy_lat,
colorscale=colorscale,
line_color=line_colors['marker'],
legendgroup=None,
)
# Legend title
fig.update_layout(
legend_title_text=plotlabels['sizelabel'],
legend_itemclick=False,
legend_itemdoubleclick=False,
)
fig.update_layout(legend_itemsizing='trace')
# change margins to smaller than default to get map to be bigger
fig.update_layout(margin=dict(l=30,b=20))
# Only display this specific geography, not whole world
fig.update_geos(fitbounds='locations', visible=False)
# plot and save as html, with plotly JS library loaded from CDN
fig.write_html(
file=savefile,
default_height=fig_height,
include_plotlyjs='cdn',
)
# show the figure
if showfig:
os.startfile(savefile)
return fig
def plotly_changebubble(
geodata,
currcol,
pastcol,
colorcol,
popcol='Population',
size_factor=1,
color_range=[0, 600],
colorscale=None,
location_names=None,
plotlabels=None,
savefile='.\\temp.html',
fig_height='100%',
showfig = True,
):
"""Create interactive plotly map figure, with bubbles that show size and color
geodata -- GeoPandas DataFrame
currcol -- Column to use for current bubble sizes
pastcol -- Column to use for past bubble sizes
colorcol -- Column to use for bubble color
fig_height -- html tag for height of the figure. Default is to fill the div; could also specify pixels.
showfig -- flag for displaying the figure after it is created
"""
# Input process plotlabels
plotlabels_default = dict(title='Color-Bubble Map',
sizelabel=currcol,
colorlabel=colorcol,
sizelegend=currcol,
colorlegend=colorcol,
)
if plotlabels is not None:
# replace default values with the passed values
for n in plotlabels.keys():
plotlabels_default[n] = plotlabels[n]
# then overwrite
plotlabels = plotlabels_default
# Colors for the background map (not used) and marker lines
line_colors = {'land':'lightgray', 'border':'darkgray', 'marker':'dimgray', 'past': 'gray'}
# Background map
fig = plotly_backmap(geodata)
fig.update_layout(title=plotlabels['title'])
# Get latitude and longitude of centroids for plotting the bubbles,
# if not already set.
# This will give warning but I don't care
if 'plotlon' not in geodata.columns:
geodata['plotlon'] = geodata.geometry.centroid.x
if 'plotlat' not in geodata.columns:
geodata['plotlat'] = geodata.geometry.centroid.y
# Create display names for tooltip
if location_names is None:
location_names = geodata.index
# Convert to numpy array so can be logically indexed
location_names = np.array(location_names)
# Set any values < 0 to 0
geodata[currcol] = geodata[currcol].apply(lambda x: max(x,0))
# Sort increased and decreased locations
# Have both a proportional threshold and an absolute number threshold for
# when to display a concentric circle for change vs. only one circle for
# negligible change.
threshold = 0.2
minchange = 10*size_factor
increasefrac = geodata[currcol] / geodata[pastcol]
increaseabs = abs(geodata[currcol] - geodata[pastcol])
pick_increased = np.array((increasefrac > (1+threshold)) & (increaseabs > minchange))
pick_decreased = np.array((increasefrac < (1-threshold) ) & (increaseabs > minchange))
pick_neither = ~(pick_increased | pick_decreased)
increased = geodata[pick_increased]
decreased = geodata[pick_decreased]
neither = geodata[pick_neither]
# Create bubbles for increased locations
# Outer - purple, current numbers
fig.add_trace(
go.Scattergeo(
lon=increased.plotlon,
lat=increased.plotlat,
text=location_names[pick_increased],
customdata=increased[popcol],
marker=dict(
size=2*increased[currcol] - increased[pastcol],
sizeref=size_factor,
sizemode='area',
color='darkmagenta',
# color=increased[colorcol],
# cmin=color_range[0],
# cmax=color_range[1],
# colorscale='Reds',
opacity=0.7,
),
line=dict(color=line_colors['marker']),
# hovertemplate=
# '<b>%{text}</b><br>' +
# 'Population: %{customdata:.0f}<br>' +
# plotlabels['sizelabel'] + ' : %{marker.size:.1f}<br>' +
# plotlabels['colorlabel'] + ' : %{marker.color:.1f}'+
# '<extra></extra>',
# No hover info, it was included in the previous bubble plot
hovertemplate=None,
hoverinfo='skip',
showlegend=True,
legendgroup='Increase',
name='Increase',
)
)
# Inner - blue, past numbers
fig.add_trace(
go.Scattergeo(
lon=increased.plotlon,
lat=increased.plotlat,
text=location_names[pick_increased],
customdata=increased[popcol],
# customdata=(increased[popcol], increased[currcol]/increased[pastcol]-1),
marker=dict(
size=increased[currcol],
sizeref=size_factor,
sizemode='area',
# color='white',
color=increased[colorcol],
cmin=color_range[0],
cmax=color_range[1]*1.1, # times 1.x to make the color lighter, to make up for the overlap over the existing marker
colorscale=colorscale,
opacity=1,
# colorbar=dict(
# title=plotlabels['colorlabel'],
# yanchor='bottom',
# y=0.6,
# len=0.25,
# thickness=12,
# ),
),
line=dict(color=line_colors['past']),
hovertemplate=
'<b>%{text}</b><br>' +
'Population: %{customdata:.0f}<br>' +
# 'Population: %{customdata[0]:.0f}<br>' +
plotlabels['sizelabel'] + ' : %{marker.size:.1f}<br>' +
plotlabels['colorlabel'] + ' : %{marker.color:.1f}'+
'<extra></extra>',
# '<extra>%{customdata[1]:.0%}</extra>',
showlegend=False,
legendgroup='Current',
)
)
# Create bubbles no change locations
fig.add_trace(
go.Scattergeo(
lon=neither.plotlon,
lat=neither.plotlat,
text=location_names[pick_neither],
customdata=neither[popcol],
marker=dict(
size=neither[currcol],
sizeref=size_factor,
sizemode='area',
color=neither[colorcol],
cmin=color_range[0],
cmax=color_range[1],
colorscale=colorscale,
opacity=0.8,
colorbar=dict(
title=plotlabels['colorlabel'],
yanchor='bottom',
y=0.6,
len=0.25,
thickness=12,
),
),
line=dict(color=line_colors['marker']),
hovertemplate=
'<b>%{text}</b><br>' +
'Population: %{customdata:.0f}<br>' +
plotlabels['sizelabel'] + ' : %{marker.size:.1f}<br>' +
plotlabels['colorlabel'] + ' : %{marker.color:.1f}'+
'<extra></extra>',
showlegend=True,
legendgroup='Current',
name='Current',
)
)
# Create bubbles for decreased locations
# Outer - past data
fig.add_trace(
go.Scattergeo(
lon=decreased.plotlon,
lat=decreased.plotlat,
customdata=decreased[popcol],
marker=dict(
size=decreased[pastcol],
sizeref=size_factor,
sizemode='area',
color='rgba(255,255,255,0.3)', # low opacity for fill
# color=decreased[colorcol],
# cmin=color_range[0],
# cmax=color_range[1],
# colorscale='Greys',
),
line=dict(color=line_colors['past']),
# No hover info, it will be included in the next bubble plot
hovertemplate=None,
hoverinfo='skip',
showlegend=True,
legendgroup='Decrease',
name='Decrease'
)
)
# Inner - current data
fig.add_trace(
go.Scattergeo(
lon=decreased.plotlon,
lat=decreased.plotlat,
text=location_names[pick_decreased],
customdata=decreased[popcol],
marker=dict(
size=decreased[currcol],
sizeref=size_factor,
sizemode='area',
color=decreased[colorcol],
cmin=color_range[0],
cmax=color_range[1],
colorscale=colorscale,
opacity=0.8,
colorbar=dict(
title=plotlabels['colorlabel'],
yanchor='bottom',
y=0.6,
len=0.25,
thickness=12,
),
),
line=dict(color=line_colors['marker']),
hovertemplate=
'<b>%{text}</b><br>' +
'Population: %{customdata:.0f}<br>' +
plotlabels['sizelabel'] + ' : %{marker.size:.1f}<br>' +
plotlabels['colorlabel'] + ' : %{marker.color:.1f}'+
'<extra></extra>',
showlegend=False,
legendgroup='Current',
)
)
# Add bubble legend (using dummy traces)
# find dummy locations - put outside the map and hide with a white circle
lon_range = np.abs(geodata.plotlon.max() - geodata.plotlon.min())
idx = geodata.plotlon.idxmax()
dummy_lon = geodata.plotlon[idx] + 0.1*lon_range
dummy_lat = geodata.plotlat[idx]
# Bubble legend
# covid.plotly_add_bubblelegend(
# fig,
# sizeref=size_factor,
# dummy_lon=dummy_lon,
# dummy_lat=dummy_lat,
# colorscale=colorscale,
# line_color=line_colors['marker'],
# legendgroup=None,
# )
# Legend title
fig.update_layout(
legend_title_text=plotlabels['sizelabel'],
# legend_itemclick=False,
# legend_itemdoubleclick=False,
)
fig.update_layout(legend_itemsizing='constant')
# change margins to smaller than default to get map to be bigger
fig.update_layout(margin=dict(l=30,b=20))
# Only display this specific geography, not whole world
fig.update_geos(fitbounds='locations', visible=False)
# plot and save as html, with plotly JS library loaded from CDN
fig.write_html(
file=savefile,
default_height=fig_height,
include_plotlyjs='cdn',
)
# show the figure
if showfig:
os.startfile(savefile)
return fig
def plotly_backmap(geodata):
"""Helper function for creating a background map.
The background map figure can then be used as the base layer of
plotly.graph_objects.Scattergeo plots.
geodata -- GeoPandas GeoDataFrame object that contains the geometry
of the map to be drawn.
"""
# Plotly needs a JSON format string for plotting arbitrary shapes, so -
# convert geodata to JSON format string, then decode to dictionary with json.loads()
geoJS = json.loads(geodata.to_json())
# Colors for the background map
line_colors = {'land':'lightgray', 'border':'darkgray', 'marker':'dimgray'}
# Background map
fig = px.choropleth(
geodata,
geojson=geoJS,
locations=geodata.index,
color_discrete_sequence=[line_colors['land']],
projection='mercator',
)
# turn off hover tooltips for this layer - have to set both of these because
# hovertemplate is set automatically and it supersedes hoverinfo.
# Also take out legend, change border color.
fig.update_traces(
hovertemplate=None,
hoverinfo='skip',
marker_line_color=line_colors['border'],
showlegend=False,
)
# Only display this specific geography, not whole world
fig.update_geos(fitbounds='locations', visible=False)
return fig
def plotly_add_bubblelegend(
fig,
sizeref,
dummy_lon,
dummy_lat,
colorscale=None,
fill_color=[1],
line_color='dimgray',
legendgroup=None):
""" Helper function to create a bubble map legend using dummy traces.
In plotly, bubble map legends do not show different sizes of bubbles
with their quantities. This function uses a hack to create such a legend
by plotting separate dummy bubble traces with set sizes, but that match
the desired style, sizeref, and legendgroup of the real plot, and
creating a legend for these dummy traces.
The biggest limitation to the hack is that the dummy bubbles need to
really exist and be plotted, so they need to be placed in a dummy
longitude/latitude location where they can be covered up by a blank white
marker without interfering with anything else in the plot.
Areas for improvement: pull marker colors from the figure; get around
needing dummy lon/lat values.
fig -- Existing figure in which to create the legend.
sizeref -- The same sizeref parameter used for the real bubble plot.
dummy_lon, -- Longitude/latitude values at which to plot the dummy bubbles.
dummy_lat
colorscale -- Named colorscale used for real bubble map, if needed.
fill_color -- Fill color of the bubble markers. Default [1] makes it the
middle of colorscale.
line_color -- Line color of the bubble markers.
legendgroup -- Legend group name. If you want the legend to properly
toggle on/off the real bubble plot, it needs to have the same
legendgroup name as the real plot. If not None, then the function
will insert a title into the legend for this legendgroup.
"""
# Max size in pixels from web search and experiment;
# then convert to sizes in the units of the bubble plot
legend_marker_pixel_max = 16 # diameter
legend_marker_size_max = (legend_marker_pixel_max)**2 * sizeref / 2
sizes_marker = np.array([1, 0.25]) * legend_marker_size_max
# round to nearest first significant digit
power10 = 10**np.floor(np.log10(sizes_marker))
sizes_marker = np.round(sizes_marker / power10) * power10
# round up to whole integer in case lowest is < 1
sizes_marker = np.ceil(sizes_marker)
# convert to pixel diameter scale
sizes_pixel = np.round(np.sqrt(sizes_marker/sizeref*2))
# create text labels
sizes_names = [str(int(s)) for s in sizes_marker]
if legendgroup is not None:
# create dummy trace with group title
fig.add_trace(
go.Scattergeo(
lon=[dummy_lon], # just dummy locations
lat=[dummy_lat],
name='<br>'+legendgroup,
marker=dict(size=0, opacity=0),
showlegend=True,
legendgroup=legendgroup,
hovertemplate=None,
hoverinfo='skip',
)
)
# create dummy bubbles with the sizes required
for ss in range(len(sizes_pixel)):
fig.add_trace(
go.Scattergeo(
lon=[dummy_lon], # just dummy locations
lat=[dummy_lat],
name=sizes_names[ss],
marker=dict(
size=sizes_pixel[ss],
sizemode='area',
colorscale=colorscale,
color=fill_color,
line=dict(color=line_color, width=1),
),
showlegend=True,
legendgroup=legendgroup,
hovertemplate=None,
hoverinfo='skip',
)
)
# plot a white marker over the top to hide them
fig.add_trace(
go.Scattergeo(
lon=[dummy_lon],
lat=[dummy_lat],
marker=dict(
size=legend_marker_pixel_max+3,
color='white',
opacity=1,
),
showlegend=False,
legendgroup='camouflage',
hovertemplate=None,
hoverinfo='skip',
),
)
def plotly_casetest(
sourcedata,
case_col,
test_col,
plotcolors=['steelblue','olivedrab','lightsteelblue'],
secondary_scale=10,
plotlabels = {'title': 'WI Daily Cases and New People Tested',
'yaxis': 'Cases',
'yaxis_secondary': 'New people tested',
},
**kwargs,
):
"""Create interactive plotly figure for cases and tests.
This is a wrapper for plotly_twolines with two differences. First, column1
and column2 are renamed to the more explicit case_col and test_col. Second,
a number of layout parameters are given default values. These layout
parameters can still be overridden.
"""
plotly_twolines(
sourcedata,
case_col,
test_col,
plotcolors=plotcolors,
secondary_scale=secondary_scale,
plotlabels=plotlabels,
**kwargs,
)
def plotly_deadhosp(
sourcedata,
dead_col,
hosp_col,
plotcolors=['firebrick', 'darkorange', 'rosybrown'],
secondary_scale=1,
plotlabels=dict(title='WI Daily Deaths and Hospitalizations',
yaxis='Deaths / Hospitalizations',
),
**kwargs,
):
"""Create interactive plotly figure for deaths and hospitalizations.
This is a wrapper for plotly_twolines with two differences. First, column1
and column2 are renamed to the more explicit dead_col and hosp_col. Second,
a number of layout parameters are given default values. These layout
parameters can still be overridden.
"""
plotly_twolines(
sourcedata,
dead_col,
hosp_col,
plotcolors=plotcolors,
secondary_scale=secondary_scale,
plotlabels=plotlabels,
**kwargs,
)
def plotly_twolines(
sourcedata,
column1,
column2,
date_col='Date',
plotcolors=None,
savefile='.\\temp.html',
groupby=None,
grouplist=None,
groupcolors=None,
ncol=None,
secondary_scale=1,
range_max=None,
date_min=None,
col1_mode='avg-bar',
col2_mode='avg',
plotlabels=None,
fig_height='100%',
showfig = True,
):
"""Create interactive plotly figure of two quantities.
sourcedata -- a DataFrame containing the data to plot
column1 -- name of first column to plot
column2 -- name of second column to plot
date_col -- name of column containing datetime objects as x-axis
plotcolors -- colors for the three possible plots, in the order [column1 avg, column2 avg, column1 non-avg]
savefile -- full path of file for saving the html of the figure
groupby -- name of column to use for splitting into a plot grid, such as region
grouplist -- list of members of groupby to plot. If None then plot first 9.
groupcolors -- colors for outlining subplots, corresponding to entries in grouplist
ncol -- number of columns for a plot grid. If None then use close to sqrt of groups
secondary_scale -- scale factor of secondary axis, for column2. Max of secondary axis will be (scale) times larger than primary.
range_max -- max for primary y scale. Actual max will be padded by 5%. If None, then auto-calculate.
date_min -- min date for x axis. If None then use all.
column1_bar -- if True, plot both an average line and a daily bar chart for column1. If False, only the line.
col1_mode -- mode for column 1 - 'avg-bar' (plot both a 7-day average line and daily bars), 'avg' (only 7-day avg), 'bar' (only bar), 'line' (only line, no processing)
col2_mode -- mode for column 2 - 'avg' (plot line of 7-day avg), 'line' (just plot the values with a line)
plotlabels -- dict containing strings for 'title', 'yaxis', 'yaxis_secondary'
fig_height -- html tag for height of the figure. Default is to fill the div; could also specify pixels.
showfig -- flag for displaying the figure after it is created
"""
# misc input processing - plotcolors
plotcolors_default = ['black', 'red', 'gray']
if type(plotcolors_default) is not list:
plotcolors = plotcolors_default
elif len(plotcolors) < 3:
plotcolors_in = plotcolors
plotcolors = plotcolors_default
plotcolors[0:len(plotcolors_in)] = plotcolors_in
# secondary yaxis - if secondary_scale != 1, then have a second y-axis
secondary_y = (secondary_scale != 1)
# plotlabels
if plotlabels is None:
if secondary_y:
plotlabels = {'title': column1+' and '+column2, 'yaxis': column1, 'yaxis_secondary': column2}
else:
plotlabels = {'title': column1+' and '+column2, 'yaxis': column1+' / '+column2, 'yaxis_secondary': ''}
# input processing for groupby and grouplist
# make sure grouplist is always a list, even with one element, and
# cases/secondary always a 2d DataFrame, even with one column
if groupby is None:
grouplist = ['All']
data1 = pd.DataFrame({'All': sourcedata.set_index(date_col)[column1]})
data2 = pd.DataFrame({'All': sourcedata.set_index(date_col)[column2]})
else:
data1 = sourcedata.pivot(index=date_col, columns=groupby, values=column1)
data2 = sourcedata.pivot(index=date_col, columns=groupby, values=column2)
if grouplist is None:
# take all the columns, or the first 9, whichever is smaller
grouplist = data1.columns
if len(grouplist) > 9:
print('Displaying only the first 9 ' + groupby + 'categories.')
grouplist = grouplist[0:10]
elif type(grouplist) is not list:
grouplist = [grouplist]
# select only the data in the group, first taking out blank entries
select = grouplist.copy()
if None in select:
select.remove(None)
if '' in select:
select.remove('')
data1 = data1[select]
data2 = data2[select]
# create variables for 7-day average
avg1 = data1.rolling(window=7, center=False).mean()
avg2 = data2.rolling(window=7, center=False).mean()
# create labels
data1_label = column1
data2_label = column2
avg1_label = data1_label + ' (7-day avg)'
avg2_label = data2_label + ' (7-day avg)'
# create layout of plot grid
nplots = len(grouplist)
if ncol is None:
ncol = int(np.ceil(np.sqrt(nplots)))
nrow = int(np.ceil(nplots/ncol))
# make subplot grid
if nplots > 1:
sub_titles = grouplist
else:
sub_titles = None
sub_spec = [[{"secondary_y": secondary_y}]*ncol]*nrow
fig = plotly.subplots.make_subplots(
rows=nrow,
cols=ncol,
subplot_titles=sub_titles,
horizontal_spacing=0.03,
vertical_spacing=0.03,
specs=sub_spec,
)
# Subplot title annotation - shrink font size and move inside plot box
for subtitle in fig['layout']['annotations']:
subtitle['font'] = dict(size=14) # default is 16
subtitle['yanchor'] = 'top'
# keep track of row and col of each index plot
sub_row = [1] * nplots
sub_col = [1] * nplots
# loop over the plots
for gg, group in enumerate(grouplist):
# leave space blank if nothing in that spot in grouplist
if group is None or len(group)==0:
continue
sub_row[gg] = int(gg / ncol) + 1
sub_col[gg] = gg - (sub_row[gg]-1)*ncol + 1
# only include the very first set of traces in the legend
if gg == 0:
showlegend = True
else:
showlegend = False
# daily non-avg numbers bar chart for column1
if 'bar' in col1_mode:
fig.add_trace(
go.Bar(
x=data1.index,
y=data1.loc[:,group],
name=data1_label,
marker_color=plotcolors[2],
hovertemplate='%{y:.0f}',
showlegend=showlegend,
),
row=sub_row[gg],
col=sub_col[gg],
)
# 7-day average lines
if 'avg' in col1_mode:
fig.add_trace(
go.Scatter(
x=avg1.index,
y=avg1.loc[:,group],
name=avg1_label,
line_color=plotcolors[0],
hovertemplate='%{y:.1f}',
showlegend=showlegend,
),
row=sub_row[gg],
col=sub_col[gg],
secondary_y=False,
)
elif 'line' in col1_mode:
fig.add_trace(
go.Scatter(
x=data1.index,
y=data1.loc[:,group],
name=data1_label,
line_color=plotcolors[0],
hovertemplate='%{y:.1f}',
showlegend=showlegend,
),
row=sub_row[gg],
col=sub_col[gg],
secondary_y=False,
)
if 'avg' in col2_mode:
fig.add_trace(
go.Scatter(
x=avg2.index,
y=avg2.loc[:,group],
name=avg2_label,
line_color=plotcolors[1],
hovertemplate='%{y:.1f}',
showlegend=showlegend,
),
row=sub_row[gg],
col=sub_col[gg],
secondary_y=secondary_y,
)
elif 'line' in col2_mode:
fig.add_trace(
go.Scatter(
x=data2.index,
y=data2.loc[:,group],
name=data2_label,
line_color=plotcolors[1],
hovertemplate='%{y:.1f}',
showlegend=showlegend,
),
row=sub_row[gg],
col=sub_col[gg],
secondary_y=secondary_y,
)
if range_max is None:
# compute y axis range - to_numpy to make robust to multiple columns
# want secondary to be on a scale exactly 10x primary
avg1_max = avg1.to_numpy(na_value=0).max()
avg2_max = avg2.to_numpy(na_value=0).max();
range_max = max(avg1_max, avg2_max/secondary_scale)
if 'bar' in col1_mode:
data1_max = data1.to_numpy(na_value=0).max();
range_max = max(range_max, data1_max)
range_y = np.array([-range_max * 0.05, 1.05*range_max])
# compute x axis range - want to extend past the latest date just for viewing niceness
if date_min is None:
date_min = avg1.index.min()
date_max = avg2.index.max() + datetime.timedelta(days=5)
range_dates = [date_min, date_max]
# update axes for all plots
fig.update_xaxes({'range': range_dates}, showticklabels=False)
fig.update_yaxes({'range': range_y}, secondary_y=False, showticklabels=False)
# update axes for border plots
fig.update_xaxes(row=nrow, showticklabels=True)
fig.update_yaxes(col=1, secondary_y=False, showticklabels=True)
fig.update_yaxes(col=1, row=int(nrow/2)+1, secondary_y=False, title_text=plotlabels['yaxis'])
# secondary axis
if secondary_y:
fig.update_yaxes({'range': range_y*secondary_scale}, secondary_y=True, showticklabels=False)
fig.update_yaxes(col=ncol, secondary_y=True, showticklabels=True)
fig.update_yaxes(col=ncol, row=int(nrow/2)+1, secondary_y=True, title_text=plotlabels['yaxis_secondary'])
# outline subplots in group colors
if groupcolors is not None:
if len(groupcolors) == len(grouplist):
for gg, boxcolor in enumerate(groupcolors):
rr = sub_row[gg]
cc = sub_col[gg]
fig.update_xaxes(showline=True, linewidth=4, linecolor=boxcolor, mirror=True, row=rr, col=cc)
fig.update_yaxes(showline=True, linewidth=4, linecolor=boxcolor, mirror=True, row=rr, col=cc)
else:
raise ValueError('Number of elements in groupcolors does not match number of elements in grouplist.')
# Some layout updates
# - lighter background color, same as default but with lower opacity
fig.update_layout(title_text=plotlabels['title'],
hovermode='x unified',
plot_bgcolor='rgba(229, 236, 246, 0.7)',
)
if nplots == 1:
fig.update_layout(legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01))
else:
fig.update_layout(legend=dict(orientation='h', yanchor="top", y=-0.18, xanchor="center", x=0.5))
# save as html, with plotly JS library loaded from CDN
fig.write_html(
file=savefile,
default_height=fig_height,
include_plotlyjs='cdn',
)
# show the figure
if showfig:
os.startfile(savefile)
return fig
def plot_by_county(datatable, popdata, datatype, n_display=6, county_list=[]):
"""Create stacked line plot of data points by county
datatype -- column name from the datatable
n_display -- number of plots to display; n_display-1 counties and sum of remainder
county_list -- list of counties to display, may include 'Other'
If county_list is defined, then plots those counties. You can include 'Other'
in that list, which will plot the data of all counties not in the list.
If county_list is empty or not defined, then the (n_display - 1) top counties
for that datatype are displayed, plus the sum of the remainder as
'Other'.
"""
selected = select_by_county(datatable, datatype, n_display, county_list)
selected.columns.name = 'County'
# create 7-day rolling mean
avg = selected.rolling(window=7, center=True).mean()
# stacked line plot
avg.plot(kind='area')
plt.title(datatype + ' by county')
# grid of per-capita plots
per_million = 1e6 * convert_per_capita(avg, popdata)
fig, axs = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True, constrained_layout=True)
for cc, county in enumerate(per_million):