-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1058 lines (974 loc) · 46.9 KB
/
app.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
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table as dt
import pandas as pd
import numpy as np
import glob
import re
from datetime import date, timedelta
import io
import requests
# Standard plotly imports
import plotly.graph_objects as go
from plotly.offline import iplot, init_notebook_mode
# Using plotly + cufflinks in offline mode
import cufflinks
cufflinks.go_offline(connected=True)
init_notebook_mode(connected=True)
app = dash.Dash(__name__)
server = app.server
app.config.suppress_callback_exceptions=True
app.title = 'COVID-19'
def etl(source='web'):
if source=='folder':
# Load files from folder
path = 'data'
all_files = glob.glob(path + "/*.csv")
files = []
for filename in all_files:
file = re.search(r'([0-9]{2}\-[0-9]{2}\-[0-9]{4})', filename)[0]
print(file)
df = pd.read_csv(filename, index_col=None, header=0)
df['date'] = pd.to_datetime(file)
df.rename(columns={'Province_State': 'Province/State',
'Country_Region': 'Country/Region',
'Lat': 'Latitude',
'Long_': 'Longitude'}, inplace=True)
files.append(df)
elif source=='web':
# Load files from web
file_date = date(2020, 1, 22)
dates = []
while file_date <= date.today():
dates.append(file_date)
file_date += timedelta(days=1)
files = []
for file in dates:
file = file.strftime("%m-%d-%Y")
print(file)
url = r'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{}.csv'.format(file)
raw_string = requests.get(url).content
df = pd.read_csv(io.StringIO(raw_string.decode('utf-8')))
df['date'] = pd.to_datetime(file)
files.append(df)
df = pd.concat(files, axis=0, ignore_index=True, sort=False)
# Rename countries with duplicate naming conventions
df['Country/Region'].replace('Mainland China', 'China', inplace=True)
df['Country/Region'].replace('Hong Kong SAR', 'Hong Kong', inplace=True)
df['Country/Region'].replace(' Azerbaijan', 'Azerbaijan', inplace=True)
df['Country/Region'].replace('Holy See', 'Vatican City', inplace=True)
df['Country/Region'].replace('Iran (Islamic Republic of)', 'Iran', inplace=True)
df['Country/Region'].replace('Taiwan*', 'Taiwan', inplace=True)
df['Country/Region'].replace('Korea, South', 'South Korea', inplace=True)
df['Country/Region'].replace('Viet Nam', 'Vietnam', inplace=True)
df['Country/Region'].replace('Macao SAR', 'Macau', inplace=True)
df['Country/Region'].replace('Russian Federation', 'Russia', inplace=True)
df['Country/Region'].replace('Republic of Moldova', 'Moldova', inplace=True)
df['Country/Region'].replace('Czechia', 'Czech Republic', inplace=True)
df['Country/Region'].replace('Congo (Kinshasa)', 'Congo', inplace=True)
df['Country/Region'].replace('Northern Ireland', 'United Kingdom', inplace=True)
df['Country/Region'].replace('Republic of Korea', 'North Korea', inplace=True)
df['Country/Region'].replace('Congo (Brazzaville)', 'Congo', inplace=True)
df['Country/Region'].replace('Taipei and environs', 'Taiwan', inplace=True)
df['Country/Region'].replace('Others', 'Cruise Ship', inplace=True)
df['Province/State'].replace('Cruise Ship', 'Diamond Princess cruise ship', inplace=True)
df['Province/State'].replace('From Diamond Princess', 'Diamond Princess cruise ship', inplace=True)
# Replace old reporting standards
df['Province/State'].replace('Chicago', 'Illinois', inplace=True)
df['Province/State'].replace('Chicago, IL', 'Illinois', inplace=True)
df['Province/State'].replace('Cook County, IL', 'Illinois', inplace=True)
df['Province/State'].replace('Boston, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace(' Norfolk County, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace('Suffolk County, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace('Middlesex County, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace('Norwell County, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace('Plymouth County, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace('Norfolk County, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace('Berkshire County, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace('Unknown Location, MA', 'Massachusetts', inplace=True)
df['Province/State'].replace('Los Angeles, CA', 'California', inplace=True)
df['Province/State'].replace('Orange, CA', 'California', inplace=True)
df['Province/State'].replace('Santa Clara, CA', 'California', inplace=True)
df['Province/State'].replace('San Benito, CA', 'California', inplace=True)
df['Province/State'].replace('Humboldt County, CA', 'California', inplace=True)
df['Province/State'].replace('Sacramento County, CA', 'California', inplace=True)
df['Province/State'].replace('Travis, CA (From Diamond Princess)', 'California', inplace=True)
df['Province/State'].replace('Placer County, CA', 'California', inplace=True)
df['Province/State'].replace('San Mateo, CA', 'California', inplace=True)
df['Province/State'].replace('Sonoma County, CA', 'California', inplace=True)
df['Province/State'].replace('Berkeley, CA', 'California', inplace=True)
df['Province/State'].replace('Orange County, CA', 'California', inplace=True)
df['Province/State'].replace('Contra Costa County, CA', 'California', inplace=True)
df['Province/State'].replace('San Francisco County, CA', 'California', inplace=True)
df['Province/State'].replace('Yolo County, CA', 'California', inplace=True)
df['Province/State'].replace('Santa Clara County, CA', 'California', inplace=True)
df['Province/State'].replace('San Diego County, CA', 'California', inplace=True)
df['Province/State'].replace('Travis, CA', 'California', inplace=True)
df['Province/State'].replace('Alameda County, CA', 'California', inplace=True)
df['Province/State'].replace('Madera County, CA', 'California', inplace=True)
df['Province/State'].replace('Santa Cruz County, CA', 'California', inplace=True)
df['Province/State'].replace('Fresno County, CA', 'California', inplace=True)
df['Province/State'].replace('Riverside County, CA', 'California', inplace=True)
df['Province/State'].replace('Shasta County, CA', 'California', inplace=True)
df['Province/State'].replace('Seattle, WA', 'Washington', inplace=True)
df['Province/State'].replace('Snohomish County, WA', 'Washington', inplace=True)
df['Province/State'].replace('King County, WA', 'Washington', inplace=True)
df['Province/State'].replace('Unassigned Location, WA', 'Washington', inplace=True)
df['Province/State'].replace('Clark County, WA', 'Washington', inplace=True)
df['Province/State'].replace('Jefferson County, WA', 'Washington', inplace=True)
df['Province/State'].replace('Pierce County, WA', 'Washington', inplace=True)
df['Province/State'].replace('Kittitas County, WA', 'Washington', inplace=True)
df['Province/State'].replace('Grant County, WA', 'Washington', inplace=True)
df['Province/State'].replace('Spokane County, WA', 'Washington', inplace=True)
df['Province/State'].replace('Tempe, AZ', 'Arizona', inplace=True)
df['Province/State'].replace('Maricopa County, AZ', 'Arizona', inplace=True)
df['Province/State'].replace('Pinal County, AZ', 'Arizona', inplace=True)
df['Province/State'].replace('Madison, WI', 'Wisconsin', inplace=True)
df['Province/State'].replace('San Antonio, TX', 'Texas', inplace=True)
df['Province/State'].replace('Lackland, TX', 'Texas', inplace=True)
df['Province/State'].replace('Lackland, TX (From Diamond Princess)', 'Texas', inplace=True)
df['Province/State'].replace('Harris County, TX', 'Texas', inplace=True)
df['Province/State'].replace('Fort Bend County, TX', 'Texas', inplace=True)
df['Province/State'].replace('Montgomery County, TX', 'Texas', inplace=True)
df['Province/State'].replace('Collin County, TX', 'Texas', inplace=True)
df['Province/State'].replace('Ashland, NE', 'Nebraska', inplace=True)
df['Province/State'].replace('Omaha, NE (From Diamond Princess)', 'Nebraska', inplace=True)
df['Province/State'].replace('Douglas County, NE', 'Nebraska', inplace=True)
df['Province/State'].replace('Portland, OR', 'Oregon', inplace=True)
df['Province/State'].replace('Umatilla, OR', 'Oregon', inplace=True)
df['Province/State'].replace('Klamath County, OR', 'Oregon', inplace=True)
df['Province/State'].replace('Douglas County, OR', 'Oregon', inplace=True)
df['Province/State'].replace('Marion County, OR', 'Oregon', inplace=True)
df['Province/State'].replace('Jackson County, OR ', 'Oregon', inplace=True)
df['Province/State'].replace('Washington County, OR', 'Oregon', inplace=True)
df['Province/State'].replace('Providence, RI', 'Rhode Island', inplace=True)
df['Province/State'].replace('Providence County, RI', 'Rhode Island', inplace=True)
df['Province/State'].replace('Grafton County, NH', 'New Hampshire', inplace=True)
df['Province/State'].replace('Rockingham County, NH', 'New Hampshire', inplace=True)
df['Province/State'].replace('Hillsborough, FL', 'Florida', inplace=True)
df['Province/State'].replace('Sarasota, FL', 'Florida', inplace=True)
df['Province/State'].replace('Santa Rosa County, FL', 'Florida', inplace=True)
df['Province/State'].replace('Broward County, FL', 'Florida', inplace=True)
df['Province/State'].replace('Lee County, FL', 'Florida', inplace=True)
df['Province/State'].replace('Volusia County, FL', 'Florida', inplace=True)
df['Province/State'].replace('Manatee County, FL', 'Florida', inplace=True)
df['Province/State'].replace('Okaloosa County, FL', 'Florida', inplace=True)
df['Province/State'].replace('Charlotte County, FL', 'Florida', inplace=True)
df['Province/State'].replace('New York City, NY', 'New York', inplace=True)
df['Province/State'].replace('Westchester County, NY', 'New York', inplace=True)
df['Province/State'].replace('Queens County, NY', 'New York', inplace=True)
df['Province/State'].replace('New York County, NY', 'New York', inplace=True)
df['Province/State'].replace('Nassau, NY', 'New York', inplace=True)
df['Province/State'].replace('Nassau County, NY', 'New York', inplace=True)
df['Province/State'].replace('Rockland County, NY', 'New York', inplace=True)
df['Province/State'].replace('Saratoga County, NY', 'New York', inplace=True)
df['Province/State'].replace('Suffolk County, NY', 'New York', inplace=True)
df['Province/State'].replace('Ulster County, NY', 'New York', inplace=True)
df['Province/State'].replace('Fulton County, GA', 'Georgia', inplace=True)
df['Province/State'].replace('Floyd County, GA', 'Georgia', inplace=True)
df['Province/State'].replace('Polk County, GA', 'Georgia', inplace=True)
df['Province/State'].replace('Cherokee County, GA', 'Georgia', inplace=True)
df['Province/State'].replace('Cobb County, GA', 'Georgia', inplace=True)
df['Province/State'].replace('Wake County, NC', 'North Carolina', inplace=True)
df['Province/State'].replace('Chatham County, NC', 'North Carolina', inplace=True)
df['Province/State'].replace('Bergen County, NJ', 'New Jersey', inplace=True)
df['Province/State'].replace('Hudson County, NJ', 'New Jersey', inplace=True)
df['Province/State'].replace('Clark County, NV', 'Nevada', inplace=True)
df['Province/State'].replace('Washoe County, NV', 'Nevada', inplace=True)
df['Province/State'].replace('Williamson County, TN', 'Tennessee', inplace=True)
df['Province/State'].replace('Davidson County, TN', 'Tennessee', inplace=True)
df['Province/State'].replace('Shelby County, TN', 'Tennessee', inplace=True)
df['Province/State'].replace('Montgomery County, MD', 'Maryland', inplace=True)
df['Province/State'].replace('Harford County, MD', 'Maryland', inplace=True)
df['Province/State'].replace('Denver County, CO', 'Colorado', inplace=True)
df['Province/State'].replace('Summit County, CO', 'Colorado', inplace=True)
df['Province/State'].replace('Douglas County, CO', 'Colorado', inplace=True)
df['Province/State'].replace('El Paso County, CO', 'Colorado', inplace=True)
df['Province/State'].replace('Delaware County, PA', 'Pennsylvania', inplace=True)
df['Province/State'].replace('Wayne County, PA', 'Pennsylvania', inplace=True)
df['Province/State'].replace('Montgomery County, PA', 'Pennsylvania', inplace=True)
df['Province/State'].replace('Fayette County, KY', 'Kentucky', inplace=True)
df['Province/State'].replace('Jefferson County, KY', 'Kentucky', inplace=True)
df['Province/State'].replace('Harrison County, KY', 'Kentucky', inplace=True)
df['Province/State'].replace('Marion County, IN', 'Indiana', inplace=True)
df['Province/State'].replace('Hendricks County, IN', 'Indiana', inplace=True)
df['Province/State'].replace('Ramsey County, MN', 'Minnesota', inplace=True)
df['Province/State'].replace('Carver County, MN', 'Minnesota', inplace=True)
df['Province/State'].replace('Fairfield County, CT', 'Connecticut', inplace=True)
df['Province/State'].replace('Charleston County, SC', 'South Carolina', inplace=True)
df['Province/State'].replace('Spartanburg County, SC', 'South Carolina', inplace=True)
df['Province/State'].replace('Kershaw County, SC', 'South Carolina', inplace=True)
df['Province/State'].replace('Davis County, UT', 'Utah', inplace=True)
df['Province/State'].replace('Honolulu County, HI', 'Hawaii', inplace=True)
df['Province/State'].replace('Tulsa County, OK', 'Oklahoma', inplace=True)
df['Province/State'].replace('Fairfax County, VA', 'Virginia', inplace=True)
df['Province/State'].replace('St. Louis County, MO', 'Missouri', inplace=True)
df['Province/State'].replace('Unassigned Location, VT', 'Vermont', inplace=True)
df['Province/State'].replace('Bennington County, VT', 'Vermont', inplace=True)
df['Province/State'].replace('Johnson County, IA', 'Iowa', inplace=True)
df['Province/State'].replace('Jefferson Parish, LA', 'Louisiana', inplace=True)
df['Province/State'].replace('Johnson County, KS', 'Kansas', inplace=True)
df['Province/State'].replace('Washington, D.C.', 'District of Columbia', inplace=True)
# South Korea data on March 10 seems to be mislabled as North Korea
df.loc[(df['Country/Region'] == 'North Korea') & (df['date'] == '03-10-2020'), 'Country/Region'] = 'South Korea'
# Re-order the columns for readability
df = df[['date',
'Country/Region',
'Province/State',
'Confirmed',
'Deaths',
'Recovered',
'Latitude',
'Longitude']]
# Fill missing values as 0; create Active cases column
df['Confirmed'] = df['Confirmed'].fillna(0).astype(int)
df['Deaths'] = df['Deaths'].fillna(0).astype(int)
df['Recovered'] = df['Recovered'].fillna(0).astype(int)
df['Active'] = df['Confirmed'] - df['Deaths'] - df['Recovered']
# Replace missing values for latitude and longitude
df['Latitude'] = df['Latitude'].fillna(df.groupby('Province/State')['Latitude'].transform('mean'))
df['Longitude'] = df['Longitude'].fillna(df.groupby('Province/State')['Longitude'].transform('mean'))
return df
# data = etl(source='folder')
data = pd.read_csv('dashboard_data.csv')
data['date'] = pd.to_datetime(data['date'])
update = data['date'].dt.strftime('%B %d, %Y').iloc[-1]
geo_us = pd.read_csv('geo_us.csv')
colors = {
'background': '#111111',
'text': '#BEBEBE',
'grid': '#333333',
'red': '#BF0000'
}
available_countries = sorted(data['Country/Region'].unique())
states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida',
'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky',
'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',
'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico',
'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania',
'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', 'Recovered']
eu = ['Albania', 'Andorra', 'Austria', 'Belarus', 'Belgium', 'Bosnia and Herzegovina',
'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France',
'Germany', 'Greece', 'Hungary', 'Iceland', 'Ireland', 'Italy', 'Kosovo', 'Latvia', 'Liechtenstein',
'Lithuania', 'Luxembourg', 'Malta', 'Moldova', 'Monaco', 'Montenegro', 'Netherlands', 'North Macedonia', 'Norway',
'Poland', 'Portugal', 'Romania', 'San Marino', 'Serbia', 'Slovakia', 'Slovenia', 'Spain', 'Sweden',
'Switzerland', 'Turkey', 'Ukraine', 'United Kingdom', 'Vatican City']
africa = ['Senegal', 'Egypt', 'South Africa', 'Nigeria', 'Mali', 'Kenya',
'Guinea-Bissau', 'Gambia', "Cote d'Ivoire", 'Cabo Verde', 'Burkina Faso',
'Mauritania', 'Morocco', 'Zimbabwe', 'Zambia', 'Tunisia', 'Togo',
'Somalia', 'Niger', 'Madagascar', 'Libya', 'Guinea', 'Ghana', 'Gabon',
'Ethiopia', 'Eswatini', 'Eritrea', 'Equatorial Guinea', 'Djibouti','Congo',
'Congo', 'Republic of the Congo', 'Chad', 'Central African Republic', 'Cameroon',
'Benin', 'Uganda', 'Rwanda', 'Seychelles', 'Namibia', 'Liberia',
'Sudan', 'Tanzania', 'Algeria', 'Angola', 'Burundi', 'Botswana',
'Malawi', 'Mozambique', 'Sierra Leone', 'South Sudan', 'Western Sahara',
'Sierra Leone', 'Comoros','Sao Tome and Principe']
ecowas = ['Senegal', 'Nigeria', 'Mali', 'Guinea-Bissau', 'Gambia', "Cote d'Ivoire", 'Cabo Verde', 'Burkina Faso',
'Sierra Leone', 'Togo', 'Niger', 'Guinea', 'Ghana','Benin', 'Liberia']
region_options = {'Worldwide': available_countries, 'United States': states, 'Europe': eu, 'Africa': africa, 'Ecowas': ecowas}
df_us = data[data['Province/State'].isin(states)]
df_eu = data[data['Country/Region'].isin(eu)]
df_af = data[data['Country/Region'].isin(africa)]
df_ew = data[data['Country/Region'].isin(ecowas)]
df_eu = df_eu.append(pd.DataFrame({'date': [pd.to_datetime('2020-01-22'), pd.to_datetime('2020-01-23')],
'Country/Region': ['France', 'France'],
'Province/State': [np.nan, np.nan],
'Confirmed': [0, 0],
'Deaths': [0, 0],
'Recovered': [0, 0],
'Latitude': [np.nan, np.nan],
'Longitude': [np.nan, np.nan],
'Active': [0, 0]})).sort_index()
df_us.drop('Country/Region', axis=1, inplace=True)
df_us.rename(columns={'Province/State': 'Country/Region'}, inplace=True)
@app.callback(
Output('confirmed_ind', 'figure'),
[Input('global_format', 'value')])
def confirmed(view):
if view == 'Worldwide':
df = data
elif view == 'United States':
df = df_us
elif view == 'Europe':
df = df_eu
elif view == 'Africa':
df = df_af
elif view == 'Ecowas':
df = df_ew
else:
df = data
value = df[df['date'] == df['date'].iloc[-1]]['Confirmed'].sum()
delta = df[df['date'] == df['date'].unique()[-2]]['Confirmed'].sum()
return {
'data': [{'type': 'indicator',
'mode': 'number+delta',
'value': value,
'delta': {'reference': delta,
'valueformat': '.2%',
'relative': True,
'font': {'size': 25}},
'number': {'valueformat': ',',
'font': {'size': 50}},
'domain': {'y': [0, 1], 'x': [0, 1]}}],
'layout': go.Layout(
title={'text': "CUMULATIVE CONFIRMED"},
font=dict(color=colors['red']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
height=200
)
}
@app.callback(
Output('active_ind', 'figure'),
[Input('global_format', 'value')])
def active(view):
if view == 'Worldwide':
df = data
elif view == 'United States':
df = df_us
elif view == 'Europe':
df = df_eu
elif view == 'Africa':
df = df_af
elif view == 'Ecowas':
df = df_ew
else:
df = data
value = df[df['date'] == df['date'].iloc[-1]]['Active'].sum()
delta = df[df['date'] == df['date'].unique()[-2]]['Active'].sum()
return {
'data': [{'type': 'indicator',
'mode': 'number+delta',
'value': value,
'delta': {'reference': delta,
'valueformat': '.2%',
'relative': True,
'font': {'size': 25}},
'number': {'valueformat': ',',
'font': {'size': 50}},
'domain': {'y': [0, 1], 'x': [0, 1]}}],
'layout': go.Layout(
title={'text': "CURRENTLY ACTIVE"},
font=dict(color=colors['red']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
height=200
)
}
@app.callback(
Output('recovered_ind', 'figure'),
[Input('global_format', 'value')])
def recovered(view):
if view == 'Worldwide':
df = data
elif view == 'United States':
df = df_us
elif view == 'Europe':
df = df_eu
elif view == 'Africa':
df = df_af
elif view == 'Ecowas':
df = df_ew
else:
df = data
value = df[df['date'] == df['date'].iloc[-1]]['Recovered'].sum()
delta = df[df['date'] == df['date'].unique()[-2]]['Recovered'].sum()
return {
'data': [{'type': 'indicator',
'mode': 'number+delta',
'value': value,
'delta': {'reference': delta,
'valueformat': '.2%',
'relative': True,
'font': {'size': 25}},
'number': {'valueformat': ',',
'font': {'size': 50}},
'domain': {'y': [0, 1], 'x': [0, 1]}}],
'layout': go.Layout(
title={'text': "RECOVERED CASES"},
font=dict(color=colors['red']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
height=200
)
}
@app.callback(
Output('deaths_ind', 'figure'),
[Input('global_format', 'value')])
def deaths(view):
if view == 'Worldwide':
df = data
elif view == 'United States':
df = df_us
elif view == 'Europe':
df = df_eu
elif view == 'Africa':
df = df_af
elif view == 'Ecowas':
df = df_ew
else:
df = data
value = df[df['date'] == df['date'].iloc[-1]]['Deaths'].sum()
delta = df[df['date'] == df['date'].unique()[-2]]['Deaths'].sum()
return {
'data': [{'type': 'indicator',
'mode': 'number+delta',
'value': value,
'delta': {'reference': delta,
'valueformat': '.2%',
'relative': True,
'font': {'size': 25}},
'number': {'valueformat': ',',
'font': {'size': 50}},
'domain': {'y': [0, 1], 'x': [0, 1]}}],
'layout': go.Layout(
title={'text': "DEATHS TO DATE"},
font=dict(color=colors['red']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
height=200
)
}
@app.callback(
Output('worldwide_trend', 'figure'),
[Input('global_format', 'value')])
def worldwide_trend(view):
if view == 'Worldwide':
df = data
elif view == 'United States':
df = df_us
elif view == 'Europe':
df = df_eu
elif view == 'Africa':
df = df_af
elif view == 'Ecowas':
df = df_ew
else:
df = data
traces = [go.Scatter(
x=df.groupby('date')['date'].first(),
y=df.groupby('date')['Confirmed'].sum(),
name="Confirmed",
mode='lines'),
go.Scatter(
x=df.groupby('date')['date'].first(),
y=df.groupby('date')['Active'].sum(),
name="Active",
mode='lines'),
go.Scatter(
x=df.groupby('date')['date'].first(),
y=df.groupby('date')['Recovered'].sum(),
name="Recovered",
mode='lines'),
go.Scatter(
x=df.groupby('date')['date'].first(),
y=df.groupby('date')['Deaths'].sum(),
name="Deaths",
mode='lines')]
return {
'data': traces,
'layout': go.Layout(
title="{} Infections".format(view),
xaxis_title="Date",
yaxis_title="Number of Individuals",
font=dict(color=colors['text']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
xaxis=dict(gridcolor=colors['grid']),
yaxis=dict(gridcolor=colors['grid'])
)
}
@app.callback(
Output('country_select', 'options'),
[Input('global_format', 'value')])
def set_active_options(selected_view):
return [{'label': i, 'value': i} for i in region_options[selected_view]]
@app.callback(
Output('country_select', 'value'),
[Input('global_format', 'value'),
Input('country_select', 'options')])
def set_countries_value(view, available_options):
if view == 'Worldwide':
return ['China', 'Italy', 'South Korea', 'US', 'Spain', 'France', 'Germany']
elif view == 'United States':
return ['New York', 'Washington', 'California', 'Florida', 'Texas']
elif view == 'Europe':
return ['France', 'Germany', 'Italy', 'Spain', 'United Kingdom']
elif view == 'Africa':
return ['Senegal', 'Egypt', 'South Africa', 'Nigeria', 'Mali', 'Morocco',
'Algeria', "Cote d'Ivoire", 'Uganda']
elif view == 'Ecowas':
return ['Senegal', 'Nigeria', 'Mali', 'Guinea-Bissau', 'Gambia', "Cote d'Ivoire", 'Cabo Verde', 'Burkina Faso',
'Sierra Leone', 'Togo', 'Niger', 'Guinea', 'Ghana','Benin', 'Liberia']
else:
return ['China', 'Italy', 'South Korea', 'US', 'Spain', 'France', 'Germany']
@app.callback(
Output('active_countries', 'figure'),
[Input('global_format', 'value'),
Input('country_select', 'value')])
def active_countries(view, countries):
if view == 'Worldwide':
df = data
elif view == 'United States':
df = df_us
elif view == 'Europe':
df = df_eu
elif view == 'Africa':
df = df_af
elif view == 'Ecowas':
df = df_ew
else:
df = data
traces = []
for country in countries:
traces.append(go.Scatter(
x=df[df['Country/Region'] == country].groupby('date')['date'].first(),
y=df[df['Country/Region'] == country].groupby('date')['Active'].sum(),
name=country,
mode='lines'))
return {
'data': traces,
'layout': go.Layout(
title="Active Cases by Region",
xaxis_title="Date",
yaxis_title="Number of Individuals",
font=dict(color=colors['text']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
xaxis=dict(gridcolor=colors['grid']),
yaxis=dict(gridcolor=colors['grid']),
hovermode='closest'
)
}
@app.callback(
Output('stacked_active', 'figure'),
[Input('global_format', 'value'),
Input('column_select', 'value')])
def stacked_active(view, column):
if view == 'Worldwide':
df = data
scope = 1000
elif view == 'United States':
df = df_us
scope = 1000
elif view == 'Europe':
df = df_eu
scope = 1000
elif view == 'Africa':
df = df_af
scope = 50
elif view == 'Ecowas':
df = df_ew
scope = 4
else:
df = data
scope = 1000
traces = []
for region in df['Country/Region'].unique():
if df[(df['date'] == df['date'].iloc[-1]) & (df['Country/Region'] == region)]['Confirmed'].sum() > scope:
traces.append(go.Scatter(
x=df[df['Country/Region'] == region].groupby('date')['date'].first(),
y=df[df['Country/Region'] == region].groupby('date')[column].sum(),
name=region,
hoverinfo='x+y+name',
stackgroup='one',
mode='none'))
if column == 'Recovered':
traces.append(go.Scatter(
x=df[df['Country/Region'] == 'Recovered'].groupby('date')['date'].first(),
y=df[df['Country/Region'] == 'Recovered'].groupby('date')[column].sum(),
name='Unidentified State',
hoverinfo='x+y+name',
stackgroup='one',
mode='none'))
return {
'data': traces,
'layout': go.Layout(
title="{} {} Cases<br>(Regions with greater than {} confirmed cases)".format(view, column, scope),
xaxis_title="Date",
yaxis_title="Number of Individuals",
font=dict(color=colors['text']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
xaxis=dict(gridcolor=colors['grid']),
yaxis=dict(gridcolor=colors['grid']),
hovermode='closest'
)
}
@app.callback(
Output('world_map_active', 'figure'),
[Input('global_format', 'value'),
Input('date_slider', 'value')])
def world_map_active(view, date_index):
if view == 'Worldwide':
df = data
scope='world'
projection_type='natural earth'
elif view == 'United States':
df = df_us
scope='usa'
projection_type='albers usa'
elif view == 'Europe':
df = df_eu
scope='europe'
projection_type='natural earth'
elif view == 'Africa':
df = data
scope='africa'
projection_type='natural earth'
elif view == 'Ecowas':
df = data
scope='africa'
projection_type='natural earth'
else:
df = data
scope='world'
projection_type='natural earth',
# World map
date = df['date'].unique()[date_index]
df_world_map = df[df['date'] == date].groupby('Country/Region').agg({'Confirmed': 'sum',
'Longitude': 'mean',
'Latitude': 'mean',
'Country/Region': 'first'})
if date_index > 7:
idx7 = date_index - 7
else:
idx7 = 0
df_world_map['share_of_last_week'] = ((df[df['date'] == date].groupby('Country/Region')['Confirmed'].sum() -
df[df['date'] == df['date'].unique()[idx7]].groupby('Country/Region')['Confirmed'].sum()) /
df[df['date'] == date].groupby('Country/Region')['Confirmed'].sum()) * 100
df_world_map['percentage'] = df_world_map['share_of_last_week'].fillna(0).apply(lambda x: '{:.1f}'.format(x))
# Manually change some country centroids which are mislocated due to far off colonies
df_world_map.loc[df_world_map['Country/Region'] == 'US', 'Latitude'] = 39.810489
df_world_map.loc[df_world_map['Country/Region'] == 'US', 'Longitude'] = -98.555759
df_world_map.loc[df_world_map['Country/Region'] == 'France', 'Latitude'] = 46.2276
df_world_map.loc[df_world_map['Country/Region'] == 'France', 'Longitude'] = -3.4360
df_world_map.loc[df_world_map['Country/Region'] == 'United Kingdom', 'Latitude'] = 55.3781
df_world_map.loc[df_world_map['Country/Region'] == 'United Kingdom', 'Longitude'] = 2.2137
df_world_map.loc[df_world_map['Country/Region'] == 'Denmark', 'Latitude'] = 56.2639
df_world_map.loc[df_world_map['Country/Region'] == 'Denmark', 'Longitude'] = 9.5018
df_world_map.loc[df_world_map['Country/Region'] == 'Netherlands', 'Latitude'] = 52.1326
df_world_map.loc[df_world_map['Country/Region'] == 'Netherlands', 'Longitude'] = 5.2913
df_world_map.loc[df_world_map['Country/Region'] == 'Canada', 'Latitude'] = 59.050000
df_world_map.loc[df_world_map['Country/Region'] == 'Canada', 'Longitude'] = -112.833333
if pd.to_datetime(date).strftime('%Y-%m-%d') > '2020-03-22' and view == 'United States':
df_world_map = df_world_map[['Confirmed', 'share_of_last_week', 'percentage']].merge(geo_us, left_on='Country/Region', right_on='Province/State')
df_world_map['Country/Region'] = df_world_map['Province/State']
df_world_map = df_world_map[df_world_map['Country/Region'] != 'Cruise Ship']
df_world_map = df_world_map[df_world_map['Country/Region'] != 'Diamond Princess']
return {
'data': [
go.Scattergeo(
lon = df_world_map['Longitude'],
lat = df_world_map['Latitude'],
text = df_world_map['Country/Region'] + ': ' +\
['{:,}'.format(i) for i in df_world_map['Confirmed']] +\
' total cases, ' + df_world_map['percentage'] +\
'% from previous week',
hoverinfo = 'text',
mode = 'markers',
marker = dict(reversescale = False,
autocolorscale = False,
symbol = 'circle',
size = np.sqrt(df_world_map['Confirmed']),
sizeref = 5,
sizemin = 0,
line = dict(width=.5, color='rgba(0, 0, 0)'),
colorscale = 'Reds',
cmin = 0,
color = df_world_map['share_of_last_week'],
cmax = 100,
colorbar = dict(
title = "Percentage of<br>cases occurring in<br>the previous week",
thickness = 30)
)
)
],
'layout': go.Layout(
title ='Number of cumulative confirmed cases (size of marker)<br>and share of new cases from the previous week (color)',
geo=dict(scope=scope,
projection_type=projection_type,
showland = True,
landcolor = "rgb(100, 125, 100)",
showocean = True,
oceancolor = "rgb(80, 150, 250)",
showcountries=True,
showlakes=True),
font=dict(color=colors['text']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background']
)
}
@app.callback(
Output('table1', 'children'),
[Input('global_format', 'value')])
def update_datatable(view):
if view == 'Africa':
df = df_af
df = df.groupby('Country/Region')['Country/Region', 'Confirmed', 'Active',
'Recovered', 'Deaths'].agg(['last'])
df.columns = df.columns.droplevel(1)
return html.Div([
html.H4(children='COVID-19 UPDATE (Africa)',
style = {'color': 'white',
'textAlign': 'center',}),
dt.DataTable(
data=df.to_dict('rows'),
columns=[{'name': i, 'id': i} for i in df.columns],
style_header={'backgroundColor': colors['red'],
'fontWeight': 'bold',
'textAlign': 'center',
'text-transform': 'uppercase',
'color': 'white',
'border': '1px solid red',
'overflowY': 'hidden',},
style_cell_conditional=[{
'if': {'column_id': c},
'textAlign': 'center',
"fontWeight": "bold"
} for c in ['Confirmed', 'Active','Recovered', 'Deaths']],
style_data_conditional=[{
#'if': {'row_index': 'odd'},
'if': {'column_id': 'Country/Region'},
'textAlign': 'left',
"fontWeight": "bold",
'backgroundColor': colors['text'],
'text-transform': 'uppercase',
}],
#style_table={'overflowX': 'scroll'},
style_table={'maxHeight': '700px',
#'width': '100%',
'overflowY': 'scroll',
'textAlign': 'center',
#'margin' : 'auto'
#'margin-left' : 'auto',
#'margin-right' : 'auto'
},
style_cell={'minWidth': '180px',
'width': '180px',
'maxWidth': '180px',
'whiteSpace': 'normal',
},
#style_data={ 'border': '1px solid' },
#style_data = {'textAlign': 'center'},
#style_data={ 'border': '1px solid gray' },
#filtering=True,
#row_selectable="multi",
#_fixed_rows=1
),
html.Hr()
])
elif view == 'Ecowas':
df = df_ew
df = df.groupby('Country/Region')['Country/Region', 'Confirmed', 'Active',
'Recovered', 'Deaths'].agg(['last'])
df.columns = df.columns.droplevel(1)
return html.Div([
html.H4(children='COVID-19 UPDATE (ECOWAS)',
style = {'color': 'white',
'textAlign': 'center',}),
dt.DataTable(
data=df.to_dict('rows'),
columns=[{'name': i, 'id': i} for i in df.columns],
style_header={'backgroundColor': colors['red'],
'fontWeight': 'bold',
'textAlign': 'center',
'text-transform': 'uppercase',
'color': 'white',
'border': '1px solid red',
'overflowY': 'hidden',},
style_cell_conditional=[{
'if': {'column_id': c},
'textAlign': 'center',
"fontWeight": "bold"
} for c in ['Confirmed', 'Active','Recovered', 'Deaths']],
style_data_conditional=[{
#'if': {'row_index': 'odd'},
'if': {'column_id': 'Country/Region'},
'textAlign': 'left',
"fontWeight": "bold",
'backgroundColor': colors['text'],
'text-transform': 'uppercase',
}],
#style_table={'overflowX': 'scroll'},
style_table={'maxHeight': '700px',
#'width': '100%',
'overflowY': 'scroll',
'textAlign': 'center',
#'margin' : 'auto'
#'margin-left' : 'auto',
#'margin-right' : 'auto'
},
style_cell={'minWidth': '180px',
'width': '180px',
'maxWidth': '180px',
'whiteSpace': 'normal',
},
#style_data={ 'border': '1px solid' },
#style_data = {'textAlign': 'center'},
#style_data={ 'border': '1px solid gray' },
#filtering=True,
#row_selectable="multi",
#_fixed_rows=1
),
html.Hr()
])
elif view == 'Worldwide':
pass
elif view == 'United States':
pass
elif view == 'Europe':
pass
else:
pass
app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
html.H1(children='COVID-19',
style={
'textAlign': 'center',
'color': colors['text']
}
),
html.Div(children='Data last updated {} '.format(update), style={
'textAlign': 'center',
'color': colors['text']
}),
html.Div(children='Select focus for the dashboard', style={
'textAlign': 'center',
'color': colors['text']
}),
html.Div(
dcc.RadioItems(
id='global_format',
options=[{'label': i, 'value': i} for i in ['Worldwide', 'United States', 'Europe', 'Africa', 'Ecowas']],
value='Worldwide',
labelStyle={'float': 'center', 'display': 'inline-block'}
), style={'textAlign': 'center',
'color': colors['text'],
'width': '100%',
'float': 'center',
'display': 'inline-block'
}
),
html.Div(
dcc.Graph(id='confirmed_ind'),
style={
'textAlign': 'center',
'color': colors['red'],
'width': '25%',
'float': 'left',
'display': 'inline-block'
}
),
html.Div(
dcc.Graph(id='active_ind'),
style={
'textAlign': 'center',
'color': colors['red'],
'width': '25%',
'float': 'left',
'display': 'inline-block'
}
),
html.Div(
dcc.Graph(id='deaths_ind'),
style={
'textAlign': 'center',
'color': colors['red'],
'width': '25%',
'float': 'left',
'display': 'inline-block'
}
),
html.Div(
dcc.Graph(id='recovered_ind'),
style={
'textAlign': 'center',
'color': colors['red'],
'width': '25%',
'float': 'left',
'display': 'inline-block'
}
),
html.Div([
html.Div(
dcc.Graph(id='worldwide_trend'),
style={'width': '50%', 'float': 'left', 'display': 'inline-block'}
),
html.Div([
dcc.Graph(id='stacked_active'),
html.Div(dcc.RadioItems(
id='column_select',
options=[{'label': i, 'value': i} for i in ['Confirmed', 'Active', 'Recovered', 'Deaths']],
value='Active',
labelStyle={'float': 'center', 'display': 'inline-block'},
style={'textAlign': 'center',
'color': colors['text'],
'width': '100%',
'float': 'center',
'display': 'inline-block'
}),
style={'width': '100%', 'float': 'center', 'display': 'inline-block'})
],
style={'width': '50%', 'float': 'right', 'vertical-align': 'bottom'}
)],
style={'width': '98%', 'float': 'center', 'vertical-align': 'bottom'}
),
html.Div([
dcc.Graph(id='world_map_active'),
dcc.Slider(