-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoronavirus_multi-select.py
972 lines (846 loc) · 46.9 KB
/
coronavirus_multi-select.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
# Created by Meghadeep Roy Chowdhury 7/14/2020
# All rights reserved under GNU AGPLv3
# details: https://www.gnu.org/licenses/agpl-3.0.en.html
# Dash modules listed below are licensed under MIT License:
# dash, dash_core_components, dash_html_components, plotly
# details: https://opensource.org/licenses/MIT
# Flask module is licensed under BSD
# details: https://flask.palletsprojects.com/en/1.1.x/license/
import gc
import pandas as pd
import numpy as np
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from plotly.subplots import make_subplots
import flask
def convert_tuples_to_dict(tup):
# Make an empty dictionary
di = {}
# Populate the dictionary
for i, j in tup:
di.setdefault(i, []).append(j)
return di
def make_init_df_global(df):
# Set Country and State as multi-index of the dataframe
df = df.set_index(['Country/Region', 'Province/State'], drop=True)
# Keep a separate dataframe for location information
df_location = df[['Lat', 'Long']].reset_index()
# Drop location from the main dataframe
df = df.drop(labels=['Lat', 'Long'], axis=1)
# Garbage collection for low RAM systems
gc.collect()
return df, df_location
def get_transpose(df):
# Transpose high resolution data and keep the dates in columns
df = df.transpose().reset_index().rename(columns={'index': 'Date'})
# Convert Date column items from string to DateTime objects
df['Date'] = pd.to_datetime(df['Date'])
# Add a separate column for overall total values in the dataframe
df.loc[:, ('Total', 'Total')] = df.sum(axis=1)
# Garbage collection for low RAM systems
gc.collect()
return df
def make_dfs_better(df):
# Fill NaN multi-index column names with Total
df.columns = pd.MultiIndex.from_frame(df.columns.to_frame().fillna('Total'))
# Add level[1] total values for each level[0]
for i in list(df.columns.get_level_values(0).unique()):
if (i != 'Date') and (i != 'Total'):
if 'Total' not in list(df[i].columns):
df[i, 'Total'] = df[i].sum(axis=1)
# Get separate dataframe for daily increase
df_daily = df.diff(axis=0)
# Reinsert Date column in Daily Increase dataframe
df_daily['Date'] = df['Date']
# Garbage collection for low RAM systems
gc.collect()
return df, df_daily
def level1_validate(level0, level1, df):
# Make a dictionary of multi-index column names
di = convert_tuples_to_dict(np.delete(df.columns.values, 0))
# Check if level-1 values are inside level-0
return set(level1).issubset(set(di[level0[0]]))
def get_viz_data(level0, level1, df_raw, df_daily, graph_type, graph_name):
# Single selection level0
if len(level0) == 1:
# Single selection level1
if len(level1) == 1:
# Check for daily increase graph type
graph_data = []
if graph_type == 'daily':
graph_data.append(go.Scatter(x=df_daily['Date'],
y=df_daily[level0[0]][level1[0]],
name=level0[0]+' ('+level1[0]+') - '+graph_name))
# Daily Increase - 7 Day rolling average
elif graph_type == 'rolling':
rolling = df_daily.rolling(7).mean()
graph_data.append(go.Scatter(x=df_daily['Date'],
y=rolling[level0[0]][level1[0]],
name=level0[0]+' ('+level1[0]+') - '+graph_name))
# For any other graph type
else:
graph_data.append(go.Scatter(x=df_raw['Date'],
y=df_raw[level0[0]][level1[0]],
name=level0[0]+' ('+level1[0]+') - '+graph_name))
# Get current number
current_number = f'{int(list(df_raw[level0[0]][level1[0]])[-1]):,}'
# Get last increase
last_increase = f'{int(list(df_daily[level0[0]][level1[0]])[-1]):,}'
return graph_data, current_number, last_increase
# Multiple selection level1
else:
# Make multi-level1-selection raw df
multi_level1_df_raw = df_raw[level0[0]][level1]
multi_level1_df_raw['Total_temp'] = multi_level1_df_raw.sum(axis=1)
# Make multi-level1-selection daily df
multi_level1_df_daily = df_daily[level0[0]][level1]
multi_level1_df_daily['Total_temp'] = multi_level1_df_daily.sum(axis=1)
# Empty list for storing graph data
graph_data = []
# Check for daily increase graph type
if graph_type == 'daily':
for i in multi_level1_df_daily.columns.to_list():
graph_data.append(go.Scatter(x=df_daily['Date'],
y=multi_level1_df_daily[i],
name=('Total' if i == 'Total_temp' else i)+' - '+graph_name))
# Daily Increase - 7 Day rolling average
elif graph_type == 'rolling':
rolling = multi_level1_df_daily.rolling(7).mean()
for i in multi_level1_df_daily.columns.to_list():
graph_data.append(go.Scatter(x=df_daily['Date'],
y=rolling[i],
name=('Total' if i == 'Total_temp' else i)+' - '+graph_name))
# For any other graph type
else:
for i in multi_level1_df_raw.columns.to_list():
graph_data.append(go.Scatter(x=df_raw['Date'],
y=multi_level1_df_raw[i],
name=('Total' if i == 'Total_temp' else i)+' - '+graph_name))
# Get current number
current_number = f'{int(list(multi_level1_df_raw["Total_temp"])[-1]):,}'
# Get last increase
last_increase = f'{int(list(multi_level1_df_daily["Total_temp"])[-1]):,}'
return graph_data, current_number, last_increase
# Multi selection level0
else:
# Make multi-level0-selection dfs
multi_level0_df_raw = pd.DataFrame()
multi_level0_df_daily = pd.DataFrame()
for i in level0:
multi_level0_df_raw[i] = df_raw[i]['Total']
multi_level0_df_daily[i] = df_daily[i]['Total']
multi_level0_df_raw['Total_temp'] = multi_level0_df_raw.sum(axis=1)
multi_level0_df_daily['Total_temp'] = multi_level0_df_daily.sum(axis=1)
# Empty list for storing graph data
graph_data = []
# Check for daily increase graph type
if graph_type == 'daily':
for i in multi_level0_df_daily.columns.to_list():
graph_data.append(go.Scatter(x=df_daily['Date'],
y=multi_level0_df_daily[i],
name=('Total' if i == 'Total_temp' else i)+' - '+graph_name))
# Daily Increase - 7 Day rolling average
elif graph_type == 'rolling':
rolling = multi_level0_df_daily.rolling(7).mean()
for i in multi_level0_df_daily.columns.to_list():
graph_data.append(go.Scatter(x=df_daily['Date'],
y=rolling[i],
name=('Total' if i == 'Total_temp' else i)+' - '+graph_name))
# For any other graph type
else:
for i in multi_level0_df_raw.columns.to_list():
graph_data.append(go.Scatter(x=df_raw['Date'],
y=multi_level0_df_raw[i],
name=('Total' if i == 'Total_temp' else i)+' - '+graph_name))
# Get current number
current_number = f'{int(list(multi_level0_df_raw["Total_temp"])[-1]):,}'
# Get last increase
last_increase = f'{int(list(multi_level0_df_daily["Total_temp"])[-1]):,}'
return graph_data, current_number, last_increase
"""
############
GET RAW DATA
############
"""
# url_common = '~/PycharmProjects/coronavirus/'
url_common = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/'
confirmed_global = pd.read_csv(url_common + 'time_series_covid19_confirmed_global.csv')
confirmed_us = pd.read_csv(url_common + 'time_series_covid19_confirmed_US.csv')
death_global = pd.read_csv(url_common + 'time_series_covid19_deaths_global.csv')
death_us = pd.read_csv(url_common + 'time_series_covid19_deaths_US.csv')
recovered_global = pd.read_csv(url_common + 'time_series_covid19_recovered_global.csv')
# us_population = pd.read_csv(r'~/PycharmProjects/coronavirus/co-est2019-alldata.csv', encoding='latin1',
# usecols=['STATE', 'COUNTY', 'POPESTIMATE2019'], dtype=str)
# death_us_fips = death_us
"""
################
MAKE DATA USABLE
################
"""
# Suppress Pandas deep-copy error
pd.options.mode.chained_assignment = None
# Clean up raw global data
confirmed_global, confirmed_global_location = make_init_df_global(confirmed_global)
death_global, death_global_location = make_init_df_global(death_global)
recovered_global, recovered_global_location = make_init_df_global(recovered_global)
# Clean up raw US data
# Set State and County as multi-index of the dataframe and drop the columns we won't use
confirmed_us = confirmed_us.set_index(['Province_State', 'Admin2'], drop=True).drop(
labels=['Country_Region', 'UID', 'iso2', 'iso3', 'code3', 'Combined_Key'], axis=1)
# Rename Longitude column
confirmed_us = confirmed_us.rename(columns={'Long_': 'Long'})
# Keep a separate dataframe for location and FIPS information
confirmed_us_location = confirmed_us[['Lat', 'Long', 'FIPS']].reset_index()
# Drop the columns we won't use in the main dataframe
confirmed_us = confirmed_us.drop(labels=['Lat', 'Long', 'FIPS'], axis=1)
# Set State and County as multi-index of the dataframe and drop the columns we won't use
death_us = death_us.set_index(['Province_State', 'Admin2'], drop=True).drop(
labels=['Country_Region', 'UID', 'iso2', 'iso3', 'code3', 'Combined_Key'], axis=1)
# Rename Longitude column
death_us = death_us.rename(columns={'Long_': 'Long'})
# Keep a separate dataframe for location and FIPS information
death_us_location = death_us[['Lat', 'Long', 'FIPS']].reset_index()
# Drop the columns we won't use in the main dataframe
death_us = death_us.drop(labels=['Lat', 'Long', 'Population', 'FIPS'], axis=1)
# # Keep separate dataframe for population information
# us_population['POPESTIMATE2019'] = us_population['POPESTIMATE2019'].apply(int)
# us_population['FIPS'] = us_population['STATE'] + us_population['COUNTY']
# us_population = us_population.drop(labels=['STATE', 'COUNTY'], axis=1)
# fips = []
# k = 0
# while k < len(death_us_fips['FIPS']):
# try:
# fips.append(str(int(death_us_fips['FIPS'][k])))
# except ValueError:
# print('hmm')
# fips.append('')
# pass
# k += 1
# fips = pd.Series(fips).apply(lambda x: x.zfill(5))
# death_us_fips['FIPS'] = fips
# Transpose high resolution data and get overall totals
confirmed_global = get_transpose(confirmed_global)
death_global = get_transpose(death_global)
recovered_global = get_transpose(recovered_global)
confirmed_us = get_transpose(confirmed_us)
death_us = get_transpose(death_us)
# Add Country-Wise and State-Wise Totals and Daily Increase DF
confirmed_global, confirmed_global_daily = make_dfs_better(confirmed_global)
death_global, death_global_daily = make_dfs_better(death_global)
recovered_global, recovered_global_daily = make_dfs_better(recovered_global)
confirmed_us, confirmed_us_daily = make_dfs_better(confirmed_us)
death_us, death_us_daily = make_dfs_better(death_us)
"""
###################
Actual Dash Stuff
###################
"""
server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)
# Get dictionaries of states in countries
global_dropdown_dict = convert_tuples_to_dict(np.delete(confirmed_global.columns.values, 0))
# Get dictionaries of counties in states
us_dropdown_dict = convert_tuples_to_dict(np.delete(confirmed_us.columns.values, 0))
# Change Dash app title
app.title = 'COVID-19 Case Tracker'
# Graph type options
graph_type_dropdown = [{'label': 'Raw Cumulative', 'value': 'linear'},
{'label': 'Logarithmic', 'value': 'log'},
{'label': 'Daily Cases', 'value': 'daily'},
{'label': 'Daily Cases (7 Day Rolling)', 'value': 'rolling'}]
# Dash drop-down values to names dictionary
fig_graph_title = {'linear': 'Raw Cumulative', 'log': 'Logarithmic', 'daily': 'Daily Cases',
None: 'Raw Cumulative', 'rolling': 'Daily Cases (7 Day Rolling Average)'}
# Dash app layout for tabs
app.layout = html.Div([
dcc.Tabs([
dcc.Tab(label='Global Data', children=[
# Country Dropdown
html.P([
html.Label('Country/Region: '),
dcc.Dropdown(id='country-dropdown',
options=[{'label': i, 'value': i}
for i in list(global_dropdown_dict.keys())],
value='Total',
placeholder='Total',
multi=True)
], style={'width': '400px',
'fontSize': '20px',
'padding-left': '100px',
'display': 'inline-block'}),
# State Dropdown
html.P([
html.Label('State/Province: '),
dcc.Dropdown(id='state-dropdown',
value='Total',
placeholder='Total',
multi=True),
], style={'width': '400px',
'fontSize': '20px',
'padding-left': '100px',
'display': 'inline-block'}),
# Graph Type dropdown
html.P([
html.Label('Type of graph: '),
dcc.Dropdown(id='graph-type-global',
options=graph_type_dropdown,
value='linear',
placeholder='Raw Cumulative')
], style={'width': '400px',
'fontSize': '20px',
'padding-left': '100px',
'display': 'inline-block'}),
# The actual tables and graphs
dcc.Graph(id='current_numbers_global'),
dcc.Graph(id='increase_numbers_global'),
dcc.Graph(id='fig_global')
]),
dcc.Tab(label='US Specific Data', children=[
# US State Dropdown
html.P([
html.Label('State: '),
dcc.Dropdown(id='us-state-dropdown',
options=[{'label': i, 'value': i}
for i in list(us_dropdown_dict.keys())],
value=['Total'],
placeholder='Total',
multi=True)
], style={'width': '400px',
'fontSize': '20px',
'padding-left': '100px',
'display': 'inline-block'}),
# County Dropdown
html.P([
html.Label('County: '),
dcc.Dropdown(id='us-county-dropdown',
value=['Total'],
placeholder='Total',
multi=True,
disabled=False),
], style={'width': '400px',
'fontSize': '20px',
'padding-left': '100px',
'display': 'inline-block'}),
# Graph type dropdown
html.P([
html.Label('Type of graph: '),
dcc.Dropdown(id='graph-type-us',
options=graph_type_dropdown,
value='linear',
placeholder='Raw Cumulative')
], style={'width': '400px',
'fontSize': '20px',
'padding-left': '100px',
'display': 'inline-block'}),
# The actual tables and graphs
dcc.Graph(id='current_numbers_us'),
dcc.Graph(id='increase_numbers_us'),
dcc.Graph(id='fig_us')
]),
])
])
# State app drop-down callback
@app.callback([Output('state-dropdown', 'options'),
Output('state-dropdown', 'disabled')],
[Input('country-dropdown', 'value')])
def update_global_dropdown(country):
# Clear State
if not country:
country = ['Total']
# Single-select country
if len(country) == 1:
# Overall Total
if country == ['Total']:
return [{'label': 'Total', 'value': 'Total'}], True
# No state in country
elif len(global_dropdown_dict[country[0]]) == 1:
return [{'label': 'Total', 'value': 'Total'}], True
# Regular state with multiple counties
else:
return [{'label': i, 'value': i} for i in global_dropdown_dict[country[0]]], False
# Multi-select us-state
else:
return [{'label': 'Total', 'value': 'Total'}], True
# Global visualization update callback
@app.callback([Output('fig_global', 'figure'),
Output('current_numbers_global', 'figure'),
Output('increase_numbers_global', 'figure')],
[Input('country-dropdown', 'value'),
Input('state-dropdown', 'value'),
Input('graph-type-global', 'value')])
def update_figure(country, state, graph_type_global):
if (country == 'Total') or (not country) or (country == ['Total']):
country = ['Total']
state = ['Total']
# Initialize state
if not level1_validate(country, state, confirmed_global):
state = ['Total']
if len(country) == 1:
if (state == 'Total') or (not state):
state = ['Total']
if len(state) == 1:
# Default option or when user removes state option
if (country == ['Total']) or (not country):
country_input = ['Total']
state_input = ['Total']
title_confirmed = 'Confirmed Cases: Global'
confirmed_global_graph_data, confirmed_number_global, confirmed_increase_global = \
get_viz_data(country_input, state_input, confirmed_global,
confirmed_global_daily, graph_type_global, 'Confirmed')
title_death = 'Number of Deaths: Global'
death_global_graph_data, death_number_global, death_increase_global = \
get_viz_data(country_input, state_input, death_global,
death_global_daily, graph_type_global, 'Deaths')
title_recovery = 'Recovery Numbers: Global'
recovered_global_graph_data, recovery_number_global, recovered_increase_us = \
get_viz_data(country_input, state_input, recovered_global,
recovered_global_daily, graph_type_global, 'Recovered')
# Default option or when user removes state option
elif not set(state).issubset(set(global_dropdown_dict[country[0]])):
country_input = country
state_input = ['Total']
title_confirmed = 'Confirmed Cases: ' + country_input[0] + ' - ' + state_input[0]
confirmed_global_graph_data, confirmed_number_global, confirmed_increase_global = \
get_viz_data(country_input, state_input, confirmed_global,
confirmed_global_daily, graph_type_global, 'Confirmed')
title_death = 'Number of Deaths: ' + country_input[0] + ' - ' + state_input[0]
death_global_graph_data, death_number_global, death_increase_global = \
get_viz_data(country_input, state_input, death_global,
death_global_daily, graph_type_global, 'Deaths')
title_recovery = 'Recovery Numbers: ' + country_input[0] + ' - ' + state_input[0]
recovered_global_graph_data, recovery_number_global, recovered_increase_us = \
get_viz_data(country_input, state_input, recovered_global,
recovered_global_daily, graph_type_global, 'Recovered')
# When user selects everything
else:
country_input = country
state_input = state
title_confirmed = 'Confirmed Cases: ' + country_input[0] + ' - ' + state_input[0]
confirmed_global_graph_data, confirmed_number_global, confirmed_increase_global = \
get_viz_data(country_input, state_input, confirmed_global,
confirmed_global_daily, graph_type_global, 'Confirmed')
# Check if death numbers available state-wise
if set(state).issubset(set(death_global[country[0]].columns.to_list())):
state_input = state
title_death = 'Number of Deaths: ' + country_input[0] + ' - ' + state_input[0]
death_global_graph_data, death_number_global, death_increase_global = \
get_viz_data(country_input, state_input, death_global,
death_global_daily, graph_type_global, 'Deaths')
else:
state_input = ['Total']
title_death = 'Number of Deaths: ' + country_input[0] + ' - ' + state_input[0]
death_global_graph_data, death_number_global, death_increase_global = \
get_viz_data(country_input, state_input, death_global,
death_global_daily, graph_type_global, 'Deaths')
# Check if recovery numbers available state-wise
if set(state).issubset(set(recovered_global[country[0]].columns.to_list())):
state_input = state
title_recovery = 'Recovery Numbers: ' + country_input[0] + ' - ' + state_input[0]
recovered_global_graph_data, recovery_number_global, recovered_increase_us = \
get_viz_data(country_input, state_input, recovered_global,
recovered_global_daily, graph_type_global, 'Recovered')
else:
state_input = ['Total']
title_recovery = 'Recovery Numbers: ' + country_input[0] + ' - ' + state_input[0]
recovered_global_graph_data, recovery_number_global, recovered_increase_us = \
get_viz_data(country_input, state_input, recovered_global,
recovered_global_daily, graph_type_global, 'Recovered')
# Make an empty subplot figure
fig_global = make_subplots(rows=2, cols=2, specs=[[{"colspan": 2}, None], [{}, {}]],
subplot_titles=(title_confirmed, title_recovery, title_death))
# Insert traces in the figure
# Insert traces in the figure
for i in confirmed_global_graph_data:
fig_global.append_trace(i, row=1, col=1)
for i in recovered_global_graph_data:
fig_global.append_trace(i, row=2, col=1)
for i in death_global_graph_data:
fig_global.append_trace(i, row=2, col=2)
# Update size and title
fig_global.update_layout(showlegend=False, height=800,
title_text=fig_graph_title[graph_type_global] + ': ' +
list(confirmed_global['Date'])[-1].strftime('%x'))
# Check for logarithmic graph type
if graph_type_global == 'log':
fig_global.update_yaxes(type='log')
# Make current numbers table
current_numbers_global = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_number_global], [recovery_number_global],
[death_number_global]]))],
layout=go.Layout(
title=go.layout.Title(text='Current Numbers: ' +
list(confirmed_global['Date'])[-1].strftime('%x'))))
# Make last increase numbers table
increase_numbers_global = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_increase_global], [recovered_increase_us],
[death_increase_global]]))],
layout=go.Layout(
title=go.layout.Title(text='Last Increase: ' +
list(confirmed_global['Date'])[-1].strftime('%x'))))
# Update sizes of the tables
current_numbers_global.update_layout(height=250)
increase_numbers_global.update_layout(height=250)
return fig_global, current_numbers_global, increase_numbers_global
# Multi-select state
else:
country_input = country
state_input = state
title_confirmed = 'Confirmed Cases: ' + country_input[0] + ' - Selected States'
confirmed_global_graph_data, confirmed_number_global, confirmed_increase_global = \
get_viz_data(country_input, state_input, confirmed_global,
confirmed_global_daily, graph_type_global, 'Confirmed')
# Check if death numbers are available state-wise
if set(state).issubset(set(death_global[country[0]].columns.to_list())):
title_death = 'Number of deaths: ' + country_input[0] + ' - Selected States'
death_global_graph_data, death_number_global, death_increase_global = \
get_viz_data(country_input, state_input, death_global,
death_global_daily, graph_type_global, 'Deaths')
else:
state_input = ['Total']
title_death = 'Number of Deaths: ' + country_input[0] + ' - ' + state_input[0]
death_global_graph_data, death_number_global, death_increase_global = \
get_viz_data(country_input, state_input, death_global,
death_global_daily, graph_type_global, 'Deaths')
# Check if recovery numbers available state-wise
if set(state).issubset(set(recovered_global[country[0]].columns.to_list())):
state_input = state
title_recovery = 'Recovery Numbers: ' + country_input[0] + ' - Selected States'
recovered_global_graph_data, recovery_number_global, recovered_increase_us = \
get_viz_data(country_input, state_input, recovered_global,
recovered_global_daily, graph_type_global, 'Recovered')
else:
state_input = ['Total']
title_recovery = 'Recovery Numbers: ' + country_input[0] + ' - ' + state_input[0]
recovered_global_graph_data, recovery_number_global, recovered_increase_us = \
get_viz_data(country_input, state_input, recovered_global,
recovered_global_daily, graph_type_global, 'Recovered')
# Make an empty subplot figure
fig_global = make_subplots(rows=2, cols=2, specs=[[{"colspan": 2}, None], [{}, {}]],
subplot_titles=(title_confirmed, title_recovery, title_death))
# Insert traces in the figure
for i in confirmed_global_graph_data:
fig_global.append_trace(i, row=1, col=1)
for i in recovered_global_graph_data:
fig_global.append_trace(i, row=2, col=1)
for i in death_global_graph_data:
fig_global.append_trace(i, row=2, col=2)
# Update size and title
fig_global.update_layout(showlegend=True, height=800,
title_text=fig_graph_title[graph_type_global] + ': ' +
list(confirmed_global['Date'])[-1].strftime('%x'))
# Check for logarithmic graph type
if graph_type_global == 'log':
fig_global.update_yaxes(type='log')
# Make current numbers table
current_numbers_global = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_number_global], [recovery_number_global],
[death_number_global]]))],
layout=go.Layout(
title=go.layout.Title(
text='Current Numbers: ' + list(confirmed_global['Date'])[-1].strftime('%x'))))
# Make last increase numbers table
increase_numbers_global = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_increase_global], [recovered_increase_us],
[death_increase_global]]))],
layout=go.Layout(
title=go.layout.Title(text='Last Increase: ' + list(confirmed_global['Date'])[-1].strftime('%x'))))
# Update sizes of the tables
current_numbers_global.update_layout(height=250)
increase_numbers_global.update_layout(height=250)
return fig_global, current_numbers_global, increase_numbers_global
# Multi-Select Countries
else:
country_input = country
state_input = ['Total']
title_confirmed = 'Confirmed Cases: Selected Countries'
confirmed_global_graph_data, confirmed_number_global, confirmed_increase_global = \
get_viz_data(country_input, state_input, confirmed_global,
confirmed_global_daily, graph_type_global, 'Confirmed')
title_death = 'Number of Deaths: Selected Countries'
death_global_graph_data, death_number_global, death_increase_global = \
get_viz_data(country_input, state_input, death_global,
death_global_daily, graph_type_global, 'Deaths')
title_recovery = 'Recovery Numbers: Selected Countries'
recovered_global_graph_data, recovery_number_global, recovered_increase_us = \
get_viz_data(country_input, state_input, recovered_global,
recovered_global_daily, graph_type_global, 'Recovered')
# Make an empty subplot figure
fig_global = make_subplots(rows=2, cols=2, specs=[[{"colspan": 2}, None], [{}, {}]],
subplot_titles=(title_confirmed, title_recovery, title_death))
# Insert traces in the figure
for i in confirmed_global_graph_data:
fig_global.append_trace(i, row=1, col=1)
for i in recovered_global_graph_data:
fig_global.append_trace(i, row=2, col=1)
for i in death_global_graph_data:
fig_global.append_trace(i, row=2, col=2)
# Update size and title
fig_global.update_layout(showlegend=True, height=800,
title_text=fig_graph_title[graph_type_global] + ': ' + list(confirmed_global['Date'])[
-1].strftime(
'%x'))
# Check for logarithmic graph type
if graph_type_global == 'log':
fig_global.update_yaxes(type='log')
# Make current numbers table
current_numbers_global = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_number_global], [recovery_number_global],
[death_number_global]]))],
layout=go.Layout(
title=go.layout.Title(text='Current Numbers: ' + list(confirmed_global['Date'])[-1].strftime('%x'))))
# Make last increase numbers table
increase_numbers_global = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_increase_global], [recovered_increase_us],
[death_increase_global]]))],
layout=go.Layout(
title=go.layout.Title(text='Last Increase: ' + list(confirmed_global['Date'])[-1].strftime('%x'))))
# Update sizes of the tables
current_numbers_global.update_layout(height=250)
increase_numbers_global.update_layout(height=250)
return fig_global, current_numbers_global, increase_numbers_global
# County app drop-down callback
@app.callback([Output('us-county-dropdown', 'options'),
Output('us-county-dropdown', 'disabled')],
[Input('us-state-dropdown', 'value')])
def update_us_dropdown(us_state):
# Clear State
if (not us_state) or (us_state == 'Total'):
us_state = ['Total']
# Single-select us-state
if len(us_state) == 1:
# Overall Total
if us_state == ['Total']:
return [{'label': 'Total', 'value': 'Total'}], True
# No county in state
elif len(us_dropdown_dict[us_state[0]]) == 1:
return [{'label': 'Total', 'value': 'Total'}], True
# Regular state with multiple counties
else:
return [{'label': i, 'value': i} for i in us_dropdown_dict[us_state[0]]], False
# Multi-select us-state
else:
return [{'label': 'Total', 'value': 'Total'}], True
# US visualization update callback
@app.callback([Output('fig_us', 'figure'),
Output('current_numbers_us', 'figure'),
Output('increase_numbers_us', 'figure')],
[Input('us-state-dropdown', 'value'),
Input('us-county-dropdown', 'value'),
Input('graph-type-us', 'value')])
def update_us_figure(us_state, county, graph_type_us):
if (us_state == 'Total') or (not us_state) or (us_state == ['Total']):
us_state = ['Total']
county = ['Total']
# Initialize county
if not level1_validate(us_state, county, confirmed_us):
county = ['Total']
if len(us_state) == 1:
if (county == 'Total') or (not county):
county = ['Total']
if len(county) == 1:
# Default option or when user removes state option
if (us_state == ['Total']) or (not us_state):
state_input = ['Total']
county_input = ['Total']
title_confirmed = 'Confirmed Cases: US'
confirmed_us_graph_data, confirmed_number_us, confirmed_increase_us = \
get_viz_data(state_input, county_input, confirmed_us,
confirmed_us_daily, graph_type_us, 'Confirmed')
title_death = 'Number of Deaths: US'
death_us_graph_data, death_number_us, death_increase_us = \
get_viz_data(state_input, county_input, death_us,
death_us_daily, graph_type_us, 'Deaths')
# Default option or when user removes county option
elif not set(county).issubset(set(us_dropdown_dict[us_state[0]])):
state_input = us_state
county_input = ['Total']
title_confirmed = 'Confirmed Cases: ' + state_input[0] + ' - ' + county_input[0]
confirmed_us_graph_data, confirmed_number_us, confirmed_increase_us = \
get_viz_data(state_input, county_input, confirmed_us,
confirmed_us_daily, graph_type_us, 'Confirmed')
title_death = 'Number of Deaths: ' + state_input[0] + ' - ' + county_input[0]
death_us_graph_data, death_number_us, death_increase_us = \
get_viz_data(state_input, county_input, death_us,
death_us_daily, graph_type_us, 'Deaths')
# When user selects everything
else:
state_input = us_state
county_input = county
title_confirmed = 'Confirmed Cases: ' + state_input[0] + ' - ' + county_input[0]
confirmed_us_graph_data, confirmed_number_us, confirmed_increase_us = \
get_viz_data(state_input, county_input, confirmed_us,
confirmed_us_daily, graph_type_us, 'Confirmed')
# Check if death numbers available county-wise
if set(county).issubset(set(death_us[us_state[0]].columns.to_list())):
title_death = 'Number of Deaths: ' + state_input[0] + ' - ' + county_input[0]
death_us_graph_data, death_number_us, death_increase_us = \
get_viz_data(state_input, county_input, death_us,
death_us_daily, graph_type_us, 'Deaths')
else:
county_input = ['Total']
title_death = 'Number of Deaths: ' + state_input[0] + ' - ' + county_input[0]
death_us_graph_data, death_number_us, death_increase_us = \
get_viz_data(state_input, county_input, death_us,
death_us_daily, graph_type_us, 'Deaths')
title_recovery = 'Recovery Numbers: US - Total'
recovered_us_graph_data, recovery_number_us, recovered_increase_us = \
get_viz_data(['US'], ['Total'], recovered_global,
recovered_global_daily, graph_type_us, 'Recovered')
# Make an empty subplot figure
fig_us = make_subplots(rows=2, cols=2, specs=[[{"colspan": 2}, None], [{}, {}]],
subplot_titles=(title_confirmed, title_recovery, title_death))
# Insert traces in the figure
for i in confirmed_us_graph_data:
fig_us.append_trace(i, row=1, col=1)
for i in recovered_us_graph_data:
fig_us.append_trace(i, row=2, col=1)
for i in death_us_graph_data:
fig_us.append_trace(i, row=2, col=2)
# Update size and title
fig_us.update_layout(showlegend=False, height=800,
title_text=fig_graph_title[graph_type_us] + ': ' +
list(confirmed_us['Date'])[-1].strftime('%x'))
# Check for logarithmic graph type
if graph_type_us == 'log':
fig_us.update_yaxes(type='log')
# Make current numbers table
current_numbers_us = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_number_us], [recovery_number_us],
[death_number_us]]))],
layout=go.Layout(
title=go.layout.Title(text='Current Numbers: ' +
list(confirmed_us['Date'])[-1].strftime('%x'))))
# Make last increase numbers table
increase_numbers_us = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_increase_us], [recovered_increase_us],
[death_increase_us]]))],
layout=go.Layout(
title=go.layout.Title(text='Last Increase: ' +
list(confirmed_us['Date'])[-1].strftime('%x'))))
# Update sizes of the tables
current_numbers_us.update_layout(height=250)
increase_numbers_us.update_layout(height=250)
return fig_us, current_numbers_us, increase_numbers_us
# Multi-select county
else:
state_input = us_state
county_input = county
title_confirmed = 'Confirmed Cases: ' + state_input[0] + ' - Selected Counties'
confirmed_us_graph_data, confirmed_number_us, confirmed_increase_us = \
get_viz_data(state_input, county_input, confirmed_us,
confirmed_us_daily, graph_type_us, 'Confirmed')
# Check if death numbers are available county-wise
if set(county).issubset(set(death_us[us_state[0]].columns.to_list())):
county_input = county
title_death = 'Number of deaths: ' + state_input[0] + ' - Selected Counties'
death_us_graph_data, death_number_us, death_increase_us = \
get_viz_data(state_input, county_input, death_us,
death_us_daily, graph_type_us, 'Deaths')
else:
county_input = ['Total']
title_death = 'Number of Deaths: ' + state_input[0] + ' - Tots'
death_us_graph_data, death_number_us, death_increase_us = \
get_viz_data(state_input, county_input, death_us,
death_us_daily, graph_type_us, 'Deaths')
title_recovery = 'Recovery Numbers: US - Total'
recovered_us_graph_data, recovery_number_us, recovered_increase_us = \
get_viz_data(['US'], ['Total'], recovered_global,
recovered_global_daily, graph_type_us, 'Recovered')
# Make an empty subplot figure
fig_us = make_subplots(rows=2, cols=2, specs=[[{"colspan": 2}, None], [{}, {}]],
subplot_titles=(title_confirmed, title_recovery, title_death))
# Insert traces in the figure
for i in confirmed_us_graph_data:
fig_us.append_trace(i, row=1, col=1)
for i in recovered_us_graph_data:
fig_us.append_trace(i, row=2, col=1)
for i in death_us_graph_data:
fig_us.append_trace(i, row=2, col=2)
# Update size and title
fig_us.update_layout(showlegend=True, height=800,
title_text=fig_graph_title[graph_type_us] + ': ' +
list(confirmed_us['Date'])[-1].strftime('%x'))
# Check for logarithmic graph type
if graph_type_us == 'log':
fig_us.update_yaxes(type='log')
# Make current numbers table
current_numbers_us = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_number_us], [recovery_number_us],
[death_number_us]]))],
layout=go.Layout(
title=go.layout.Title(text='Current Numbers: ' + list(confirmed_us['Date'])[-1].strftime('%x'))))
# Make last increase numbers table
increase_numbers_us = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_increase_us], [recovered_increase_us],
[death_increase_us]]))],
layout=go.Layout(
title=go.layout.Title(text='Last Increase: ' + list(confirmed_us['Date'])[-1].strftime('%x'))))
# Update sizes of the tables
current_numbers_us.update_layout(height=250)
increase_numbers_us.update_layout(height=250)
return fig_us, current_numbers_us, increase_numbers_us
# Multi-Select US States
else:
state_input = us_state
county_input = ['Total']
title_confirmed = 'Confirmed Cases: Selected States'
confirmed_us_graph_data, confirmed_number_us, confirmed_increase_us = \
get_viz_data(state_input, county_input, confirmed_us,
confirmed_us_daily, graph_type_us, 'Confirmed')
title_death = 'Number of Deaths: Selected States'
death_us_graph_data, death_number_us, death_increase_us = \
get_viz_data(state_input, county_input, death_us,
death_us_daily, graph_type_us, 'Deaths')
title_recovery = 'Recovery Numbers: US - Total'
recovered_us_graph_data, recovery_number_us, recovered_increase_us = \
get_viz_data(['US'], ['Total'], recovered_global,
recovered_global_daily, graph_type_us, 'Recovered')
# Make an empty subplot figure
fig_us = make_subplots(rows=2, cols=2, specs=[[{"colspan": 2}, None], [{}, {}]],
subplot_titles=(title_confirmed, title_recovery, title_death))
# Insert traces in the figure
for i in confirmed_us_graph_data:
fig_us.append_trace(i, row=1, col=1)
for i in recovered_us_graph_data:
fig_us.append_trace(i, row=2, col=1)
for i in death_us_graph_data:
fig_us.append_trace(i, row=2, col=2)
# Update size and title
fig_us.update_layout(showlegend=True, height=800,
title_text=fig_graph_title[graph_type_us] + ': ' + list(confirmed_us['Date'])[-1].strftime(
'%x'))
# Check for logarithmic graph type
if graph_type_us == 'log':
fig_us.update_yaxes(type='log')
# Make current numbers table
current_numbers_us = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_number_us], [recovery_number_us],
[death_number_us]]))],
layout=go.Layout(
title=go.layout.Title(text='Current Numbers: ' + list(confirmed_us['Date'])[-1].strftime('%x'))))
# Make last increase numbers table
increase_numbers_us = go.Figure(
data=[go.Table(header=dict(values=[title_confirmed, title_recovery, title_death]),
cells=dict(values=[[confirmed_increase_us], [recovered_increase_us],
[death_increase_us]]))],
layout=go.Layout(
title=go.layout.Title(text='Last Increase: ' + list(confirmed_us['Date'])[-1].strftime('%x'))))
# Update sizes of the tables
current_numbers_us.update_layout(height=250)
increase_numbers_us.update_layout(height=250)
return fig_us, current_numbers_us, increase_numbers_us
app.run_server(debug=True, use_reloader=False)