-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoid_19_status_tracker_with_interactive_visualuzations.py
1162 lines (820 loc) · 39.4 KB
/
coid_19_status_tracker_with_interactive_visualuzations.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 -*-
"""Coid 19 Status Tracker with Interactive Visualuzations.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1IbBJKOrCTJR2m2WyQUJCbYlSKz-cNYmh
# **Coid 19 Status Tracker with Interactive Visualuzations**
"""
#mount google drive to read uploaded shapefile
from google.colab import drive
drive.mount('/content/drive')
#install geopandas
!pip install git+git://github.com/geopandas/geopandas.git
"""#### **Import Dependencies**"""
# Commented out IPython magic to ensure Python compatibility.
from datetime import date
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
import seaborn as sns
import geopandas as gpd
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from IPython.display import Markdown as md
import plotly.io as pio
import warnings
warnings.filterwarnings("ignore")
import os
if not os.path.exists("images"):
os.mkdir("images")
"""#### **Import Theme Templates & Colours palets**"""
#plotly available templates
pio.templates
"""#### **Plotly Colours** :
###### *aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen*
### **Geopandas Colous**
##### *'Grays' is not a valid value for name; supported values are 'Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap', 'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd', 'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r', 'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia', 'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot', 'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cividis', 'cividis_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'crest', 'crest_r', 'cubehelix', 'cubehelix_r', 'flag', 'flag_r', 'flare', 'flare_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r', 'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r', 'hot', 'hot_r', 'hsv', 'hsv_r', 'icefire', 'icefire_r', 'inferno', 'inferno_r', 'jet', 'jet_r'*
## **Getting Know About the Dataset**
#### Import Datasets
"""
#live covid 19 datset
df_raw = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv')
#world geopatial boundaries for plot maps
regions = gpd.read_file("/content/drive/MyDrive/Colab Materials/Geospatial World Boundaries/WB_countries_Admin0_10m.shp")
df_raw.head()
df_raw.shape
#last 5 rows
df_raw.tail()
df_raw.sample(5)
"""### **Derive World Data From The Dataset**"""
#derive world data from the dataframe
#filter data
world_all = df_raw[(df_raw['location']=='World')]
world_all = world_all[['date', 'total_cases', 'new_cases', 'total_deaths', 'new_deaths', 'people_vaccinated', 'people_fully_vaccinated','population']]
#calculate percentage
world_all['wo_cas_per'] = round((world_all['total_cases'] / world_all['population']) * 100 , 2)
world_all['wo_vc_per'] = round((world_all['people_vaccinated'] / world_all['population']) * 100 , 2)
world_all['wo_fl_vc_per'] = round((world_all['people_fully_vaccinated'] / world_all['population']) * 100 , 2)
world_all['wo_de_per'] = round((world_all['total_deaths'] / world_all['population']) * 100 , 2)
#get the last date data points
world_all = world_all.iloc[:-1,:]
world = world_all.tail(1)
#define neccesery values into the variables
vaccine_percentage_world = np.array(world['wo_vc_per'])[0]
fully_vaccine_percentage_world = np.array(world['wo_fl_vc_per'])[0]
cases_percentage_world = np.array(world['wo_cas_per'])[0]
deaths_percentage_world = np.array(world['wo_de_per'])[0]
#convert neccesery values into the variables
ca = round(np.array(world['total_cases'])[0] / 1000000,1)
de = round(np.array(world['total_deaths'])[0] / 1000000,1)
vc = round(np.array(world['people_vaccinated'])[0] / 1000000,1)
fvc = round(np.array(world['people_fully_vaccinated'])[0] / 1000000,1)
#world dreived data
world_all
#Summary of on the recent date
world
#remove world data from the main dataset
df_raw = pd.DataFrame(df_raw[~(df_raw['continent'].isnull())])
#remove data regarding to recent date
#this recent date we cant use directy for the analysis, becasue this dataset only contain the complete updated data that 2 days before the recent date. therefore we have to change the date)
print("Last Date Data Recorded",df_raw['date'].max())
print(' ')
rec_fully_up_date = df_raw['date'].iloc[-1] #derive fully update date into a variable
#filter data which under the fully complated date
df = pd.DataFrame(df_raw[~(df_raw['date'] == rec_fully_up_date )])
#derive neccessery columns for the further calculatins
df = df[['date','continent', 'location','total_tests','new_tests' ,'total_cases' ,'new_cases' ,'total_deaths' ,'new_deaths', 'total_vaccinations' ,'people_vaccinated' ,'people_fully_vaccinated' ,'population']]
#check after data cleaned
df.tail()
df.shape
for columns in df.columns:
print(columns)
df.info()
df.isnull().sum()
"""## **Pre Processing**
### **Define Dataframes for the further analysis**
### *Country Wise Dataframe*
"""
#list of countries in the dataset
country_count = len(df['location'].unique())
md(f'## *Number of Countries in The Dataset : {country_count}*')
#filter & group data by location
Ctr_wise = pd.DataFrame(df.groupby(['location']).agg({
'total_cases':'max',
'total_deaths':'max',
'people_vaccinated':'max',
'people_fully_vaccinated':'max',
'population':'max'}).reset_index())
Ctr_wise.head()
"""### *Continent Wise Dataframe*"""
Cont_wise = pd.DataFrame(df.groupby(['continent','location']).agg({
'total_cases':'max',
'total_deaths':'max',
'people_vaccinated':'max',
'people_fully_vaccinated':'max',
'population':'max'}).reset_index())
Cont_wise = pd.DataFrame(Cont_wise.groupby('continent').agg({
'total_cases':'sum',
'total_deaths':'sum',
'people_vaccinated':'sum',
'people_fully_vaccinated':'sum',
'population':'sum'}).reset_index())
Cont_wise
"""#### *Calculate Percentage Columns*"""
# vaccination percentage countries
Ctr_wise['vacc_percentage'] = round(Ctr_wise['people_vaccinated'] / Ctr_wise['population'],2)*100
Ctr_wise['Fully_vacc_percentage'] = round(Ctr_wise['people_fully_vaccinated'] / Ctr_wise['population'],2)*100
Ctr_wise['deaths_percentage'] = round(Ctr_wise['total_deaths'] / Ctr_wise['population'],4)*100
Ctr_wise['cases_percentage'] = round(Ctr_wise['total_cases'] / Ctr_wise['population'],2)*100
Ctr_wise.head(5)
# vaccination percentage of continents
Cont_wise['vacc_percentage'] = round(Cont_wise['people_vaccinated'] / Cont_wise['population'],2)*100
Cont_wise['Fully_vacc_percentage'] = round(Cont_wise['people_fully_vaccinated'] / Cont_wise['population'],2)*100
Cont_wise['deaths_percentage'] = round(Cont_wise['total_deaths'] / Cont_wise['population'],4)*100
Cont_wise['cases_percentage'] = round(Cont_wise['total_cases'] / Cont_wise['population'],2)*100
Cont_wise
"""# **Exploratory Data Analysis & Visualizations - Global**
## **Summary of Global Covid 19 Status**
"""
#pre-process the current date
Analysis_Date = df_raw['date'].iloc[-2]
title_name = "Summary of Global Covid 19 status as at " + str(Analysis_Date)
values = [['Total Cases','Total Death Cases','Vaccinated People','Fully Vaccinated People'],
[str(ca)+str('M'), str(de)+str('M') , str(vc)+str('M') ,str(fvc)+str('M') ],
[str(cases_percentage_world)+str('%'), str(deaths_percentage_world)+str('%'), str(vaccine_percentage_world) +str('%'), str(fully_vaccine_percentage_world)+str('%')]]
fig = go.Figure(data=[go.Table(
columnorder = [1,2,3],
columnwidth = [40,20,20],
header = dict(
values = [['<b>Details</b>'] , ['<b>No of People</b>'],['<b>Percentage Value</b>']],
line_color='darkslategray',
fill_color='royalblue',
align=['center','center','center'],
font=dict(color='white', size=22),
height=70
),
cells=dict(
values=values,
line_color='darkslategray',
fill=dict(color=['white', 'white', 'white']),
align=['center', 'center', 'center'],
font_size=20,
height=70)
)
])
fig.update_layout(
title = title_name,
title_font_size = 25,
width = 1400, height = 600)
fig.show()
"""### **World Vaccination Progress Percentage**"""
fig = go.Figure(go.Indicator(
domain = {'x': [0, 1], 'y': [0, 1]},
value = vaccine_percentage_world,
mode = "gauge+number+delta",
title = {'text': "World Vaccination Progress (At least 1 Dose)"},
delta = {'reference':100},
gauge = {'axis': {'range': [None, 100]},
'bar': {'color': "darkblue"},
'threshold' : {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': 99}}))
fig.show()
"""### **World Fully Vaccination Progress Percentage**"""
fig = go.Figure(go.Indicator(
domain = {'x': [0, 1], 'y': [0, 1]},
value = fully_vaccine_percentage_world,
mode = "gauge+number+delta",
title = {'text': "World Fully Vaccination Progress"},
delta = {'reference':100},
gauge = {'axis': {'range': [None, 100]},
'bar': {'color': "orange"},
'threshold' : {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': 99}}))
fig.show()
"""## **Time Line of World Data**"""
world_all.head(5)
"""### **Time Series Of Covid 19 Positive Cases**"""
fig = go.Figure()
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['total_cases'],
mode = 'lines',
line=dict(width=0.5, color='yellowgreen'),stackgroup = 'one'))
fig.update_layout(
title = "Time Series Of Covid 19 Cases",
title_font_size = 25, legend_font_size = 10,
width = 1400, height = 620)
fig.update_xaxes(
title_text = 'Year',
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.update_yaxes(
title_text = "Cases",
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.show()
"""### **Time Series Of Covid 19 Deaths**"""
fig = go.Figure()
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['total_deaths'],
mode = 'lines',
line=dict(width=0.5, color='orangered'),stackgroup = 'one'))
fig.update_layout(
title = "Time Series Of Covid 19 Death Cases",
title_font_size = 25, legend_font_size = 10,
width = 1400, height = 620)
fig.update_xaxes(
title_text = 'Year',
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.update_yaxes(
title_text = "Death Cases",
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.show()
"""### **Time Series Of Covid 19 Vaccination**"""
fig = go.Figure()
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['people_vaccinated'],
mode = 'lines',
line=dict(width=0.5, color='royalblue'),stackgroup = 'one'))
fig.update_layout(
title = "Time Series Of Covid 19 Vaccination Progress",
title_font_size = 25, legend_font_size = 10,
width = 1400, height = 620)
fig.update_xaxes(
title_text = 'Year',
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.update_yaxes(
title_text = "Vaccination Count",
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.show()
"""### **Time Series Of Covid 19 Fully Vaccinations**"""
fig = go.Figure()
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['people_fully_vaccinated'],
mode = 'lines',
line=dict(width=0.5, color='purple'),stackgroup = 'one'))
fig.update_layout(
title = "Time Series Of Covid 19 Fully Vaccination Progress",
title_font_size = 25, legend_font_size = 10,
width = 1400, height = 620)
fig.update_xaxes(
title_text = 'Year',
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.update_yaxes(
title_text = "Vaccination Count",
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.show()
"""### **Deaths vs Positive Cases Time Series**"""
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['total_cases'],
mode = 'lines',
name='Positive Cases',
line=dict(width=2, color='yellowgreen')),secondary_y=False)
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['total_deaths'],
mode = 'lines',
name='Death Cases',
line=dict(width=2, color='orangered')),secondary_y=True)
fig.update_layout(
title = "Deaths Cases vs Positive Cases Time Series",
title_font_size = 25, legend_font_size = 10,
width = 1400, height = 620)
fig.update_xaxes(
title_text = 'Year',
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.update_yaxes(title_text="Total Cases", secondary_y=False)
fig.update_yaxes(title_text="Death Cases", secondary_y=True)
fig.show()
"""### **Vaccinations Vs Positive Cases Time Series**"""
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['total_cases'],
mode = 'lines',
name='Positive Cases',
line=dict(width=2, color='yellowgreen')),secondary_y=False)
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['people_vaccinated'],
mode = 'lines',
name='Vaccination',
line=dict(width=2, color='royalblue')),secondary_y=True)
fig.update_layout(
title = "Vaccination vs Positive Cases Time Series",
title_font_size = 25, legend_font_size = 10,
width = 1400, height = 620)
fig.update_xaxes(
title_text = 'Year',
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.update_yaxes(title_text="Positive Cases", secondary_y=False)
fig.update_yaxes(title_text="Vaccination", secondary_y=True)
fig.show()
"""### **Vaccinations Vs Deaths Cases Time Series**"""
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['people_vaccinated'],
mode = 'lines',
name='Vaccination',
line=dict(width=2, color='royalblue')),secondary_y=False)
fig.add_trace(go.Scatter(
x= world_all['date'], y = world_all['total_deaths'],
mode = 'lines',
name='Death Cases',
line=dict(width=2, color='orangered')),secondary_y=True)
fig.update_layout(
title = "Vaccination vs Death Cases Time Series",
title_font_size = 25, legend_font_size = 10,
width = 1400, height = 620)
fig.update_xaxes(
title_text = 'Year',
title_font=dict(size=15, family='Verdana', color='black'),
tickfont=dict(family='Calibri', color='black', size=15))
fig.update_yaxes(title_text="Vaccination", secondary_y=False)
fig.update_yaxes(title_text="Death Cases", secondary_y=True)
fig.show()
"""## **Country Wise Data Analysis & Visualization**
#### **Pre-processing**
"""
#replaced regions country names with corrected one's according to covid 19 datasets country names
regions.replace(to_replace ={"People's Republic of China":'China',
'United States of America':'United States',
'The Bahamas':'Bahamas',
'The Gambia':'Gambia',
'Ivory Coast':"Cote d'Ivoire",
'Czech Republic':'Czechia',
'Democratic Republic of the Congo':'Democratic Republic of Congo',
'São Tomé and Príncipe':'Sao Tome and Principe',
'Vatican City':'Vatican',
'eSwatini':'Eswatini',
'Sint Maarten':'Sint Maarten (Dutch part)',
'Republic of the Congo':'Congo',
'East Timor':'Timor',
'Macau':'Macao',
'Curaçao':'Curacao',
'Pitcairn Islands':'Pitcairn',
'Faroe Islands':'Faeroe Islands',
'Republic of Macedonia':'North Macedonia',
'Federated States of Micronesia':'Micronesia (country)'},
value =None,inplace=True)
#rename regions column name for merge
regions.rename({'NAME_EN':'location'}, axis=1,inplace=True)
#merege two dataframes ( ctr_wise & regions)
mg_cont = regions.merge(Ctr_wise, on='location', how='left')
#select neccessery columns from the entire dataframe
mg_cont = mg_cont[['location','geometry','total_cases','total_deaths','people_vaccinated','people_fully_vaccinated','vacc_percentage','Fully_vacc_percentage','deaths_percentage','cases_percentage']]
#convert to millions for better visualization 7 understand
mg_cont['total_cases'] = round(mg_cont['total_cases'] / 1000000,2)
mg_cont['people_vaccinated'] = round(mg_cont['people_vaccinated'] / 1000000,2)
mg_cont['people_fully_vaccinated'] = round(mg_cont['people_fully_vaccinated'] / 1000000,2)
#display first 5 rows of pre processed data
mg_cont.head()
"""## **Countries Total Vaccination Geospatial Visualization (At least 1 Dose)**"""
#plot total cases
mg_cont.plot(column='people_vaccinated',
figsize=(22,16),
legend=True,
legend_kwds={'label': "Total People Vaccinated (Millions)",'orientation': "horizontal"},
cmap='Blues')
"""## **Countries Fully Vaccination Geospatial Visualization**"""
#plot total cases
mg_cont.plot(column='people_fully_vaccinated',
figsize=(22,16),
legend=True,
legend_kwds={'label': "Fully Vaccinated (Millions)",'orientation': "horizontal"},
cmap='Greens')
"""### **Top 10 Countries With Highest Vaccination Percentage (At least 1 Dose)**"""
Vaccination = Ctr_wise.sort_values('vacc_percentage',ascending=False)
Vaccination_filter = Vaccination[['location','people_vaccinated','vacc_percentage', 'Fully_vacc_percentage']]
Vaccination_filter.head(10)
# visualize source reported times
Vaccination_filter_top_10 = Vaccination_filter.iloc[2:10,:]
fig = px.bar(Vaccination_filter_top_10, x=Vaccination_filter_top_10['location'],
y=Vaccination_filter_top_10['vacc_percentage'],
title = "Top 10 Countries with Highest Vaccination Percentage")
fig.show()
"""#### *This dataset is from github respository under oxford unviversity project. it contain first two countries gibralter has vaccinated people more than it's population. so i didnt able to figure out the reason. therefore removed those two countries from the visualization*
### **Countries Total Cases Geospatial Visualization**
"""
#plot total cases
mg_cont.plot(column='total_cases',
figsize=(22,16),
legend=True,
legend_kwds={'label': "Total Cases (Millions)",'orientation': "horizontal"},
cmap="Oranges")
"""### **Top 10 Countries With Highest Covid 19 Cases**"""
cases = Ctr_wise.sort_values('total_cases',ascending=False)
test_filter_highest = cases[['location','total_cases','cases_percentage']]
test_filter_highest.head(10)
"""### **Top 10 Countries With Highest Covid 19 Cases Percentage**"""
cases_pr = Ctr_wise.sort_values('cases_percentage',ascending=False)
test_filter_highest_pr = cases_pr[['location','total_cases','cases_percentage']]
test_filter_highest_pr.head(10)
"""### **Countries Total Deaths Geospatial Visualization**"""
#plot total cases
mg_cont.plot(column='total_deaths',
figsize=(22,16),
legend=True,
legend_kwds={'label': "Total Deaths",'orientation': "horizontal"},
cmap='Reds')
"""### **Top 10 Countries With Highest Death Cases**"""
deaths = Ctr_wise.sort_values('total_deaths',ascending=False)
deaths_highest = deaths[['location','total_deaths','deaths_percentage']]
deaths_highest.head(10)
"""### **Top 10 Countries With Highest Death Cases Percentage**"""
deaths_pr = Ctr_wise.sort_values('deaths_percentage',ascending=False)
deaths_highest_pr = deaths_pr[['location','total_deaths','deaths_percentage']]
deaths_highest_pr.head(10)
"""## **Continents Wise Data Analysis & Visualization**
#### **Preprocessing a Fucntion to Plot Customized Bar Graphs**
"""
#define function to ploting the graphs.
def customized_barchart(Data_frame, Attribute_name_Discrete, Attribute_name_Continious ,max_Colour_name, Rest_colour_name ,Title_name, Yaxis_name, Xaxis_name, Template_name):
#set axis colours according to theme colour
if Template_name == 'plotly_dark':
COL_TICKS = 'white'
else:
COL_TICKS = 'black'
#set max colour effect to maximum value
list_series = [i for i in Data_frame[Attribute_name_Continious]]
length = len(list_series)
colors = [Rest_colour_name,] * length
colors[list_series.index(max(list_series))] = max_Colour_name
#setting ploting figure & main propertise
fig = go.Figure(data=[go.Bar( x =Data_frame[Attribute_name_Discrete], y= Data_frame[Attribute_name_Continious], marker_color=colors )])
#add layout styles
fig.update_layout(title_text=Title_name,
title_font_size = 25, legend_font_size = 10,
width=1400, height=620,
template=Template_name)
#add xaxxes styles
fig.update_xaxes(title_text = Xaxis_name,
title_font=dict(size=15, family='Verdana', color=COL_TICKS),
tickfont=dict(family='Calibri', color=COL_TICKS, size=15))
#add yaxes styles
fig.update_yaxes(title_text = Yaxis_name,
title_font=dict(size=15, family='Verdana', color=COL_TICKS),
tickfont=dict(family='Calibri', color=COL_TICKS, size=15))
fig.show()
"""### **Contitnents With Total Vaccination Percentage (At least 1 Dose)**"""
#deaths_percentage cases_percentage
dfr = Cont_wise
attnd = 'continent'
attnc = 'vacc_percentage'
mcn = 'deepskyblue'
rcn = 'lightslategray'
tn = 'Continents Vs Total Vaccination Percentage (At least 1 Dose)'
yxn = 'Vaccinations Percentage'
xxn = 'Continents'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)
"""### **Contitnents vs Total Vaccination**"""
#deaths_percentage cases_percentage
dfr = Cont_wise
attnd = 'continent'
attnc = 'people_vaccinated'
mcn = 'deepskyblue'
rcn = 'lightslategray'
tn = 'Continents vs Vaccination (At least 1 Dose)'
yxn = 'Vaccinations'
xxn = 'Continents'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)
"""### **Continents vs Fully Vaccination Percentage**"""
#deaths_percentage cases_percentage
dfr = Cont_wise
attnd = 'continent'
attnc = 'Fully_vacc_percentage'
mcn = 'gold'
rcn = 'limegreen'
tn = 'Continents vs Total Fully Vaccination Percentage'
yxn = 'Fully Vaccinations Percentage'
xxn = 'Continents'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)
"""### **Continents vs Total Fully Vaccination**"""
dfr = Cont_wise
attnd = 'continent'
attnc = 'people_fully_vaccinated'
mcn = 'gold'
rcn = 'limegreen'
tn = 'Continents vs Total Fully Vaccination'
yxn = 'Fully Vaccinations'
xxn = 'Continents'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)
"""### **Continents vs Death Cases Percentage**"""
deaths_con = Cont_wise.sort_values('deaths_percentage',ascending=False)
deaths_con = deaths_con[['continent','total_deaths','deaths_percentage']]
deaths_con
"""### **Continents vs Death Cases Percentage**"""
dfr = Cont_wise
attnd = 'continent'
attnc = 'deaths_percentage'
mcn = 'orange'
rcn = 'mediumaquamarine'
tn = 'Continents vs Death Cases Percentage'
yxn = 'Death Cases Percentage'
xxn = 'Continents'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)
"""### **Continents vs Total Death Cases**"""
dfr = Cont_wise
attnd = 'continent'
attnc = 'total_deaths'
mcn = 'orange'
rcn = 'mediumaquamarine'
tn = 'Continents vs Total Death Cases'
yxn = 'Total Death Cases'
xxn = 'Continents'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)
"""### **Continents vs Covid 19 Cases Percentage**"""
dfr = Cont_wise
attnd = 'continent'
attnc = 'cases_percentage'
mcn = 'crimson'
rcn = 'lightslategray'
tn = 'Continents vs Total Covid 19 Cases Percentage'
yxn = 'Cases Percentage'
xxn = 'Continents'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)
"""### **Continents vs Total Covid 19 Cases**"""
dfr = Cont_wise
attnd = 'continent'
attnc = 'total_cases'
mcn = 'crimson'
rcn = 'lightslategray'
tn = 'Continents vs Total Covid 19 Cases'
yxn = 'Cases'
xxn = 'Continents'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)
"""## **Sri Lanka's Status During Covid 19 Pandemic**"""
#derive srilanka's data from the main daatset
sl_df = df[df['location']=='Sri Lanka']
sl_df['people_vaccinated'].fillna(method='ffill',inplace=True)
sl_df['people_fully_vaccinated'].fillna(method='ffill',inplace=True)
sl_df
sl_df.shape
sl_df.isnull().sum()
"""### **Pre Proccessing**"""
#get last date data
sl_summary = sl_df.tail(1)
#claculate percentages
sl_summary['ca_pr_sl'] = round(sl_summary['total_cases'] / sl_summary['population'] * 100,3)
sl_summary['de_pr_sl'] = round(sl_summary['total_deaths'] / sl_summary['population'] * 100,3)
sl_summary['vc_pr_sl'] = round(sl_summary['people_vaccinated'] / sl_summary['population'] * 100,3)
sl_summary['fvc_pr_sl'] = round(sl_summary['people_fully_vaccinated'] / sl_summary['population'] * 100,3)
#drop unwanted columns
sl_summary.drop(['continent','total_vaccinations'],axis=1,inplace=True)
#display proccesed summary data
sl_summary
# define function to plot customized line charts
def line_chart(data_li ,x_vr, y_vr, colour_li, titl, x_n, y_n ):
#defune figure
fig = go.Figure()
#define line chart
fig.add_trace(go.Scatter(
x= data_li[x_vr], y = data_li[y_vr],
mode = 'lines',
line=dict(width=3, color=colour_li)))
#add title details
fig.update_layout(
title = titl,
title_font_size = 25, legend_font_size = 10,
width = 1400, height = 620,template='plotly_dark')
#add X axis details
fig.update_xaxes(
title_text = x_n ,
title_font=dict(size=15, family='Verdana', color='white'),
tickfont=dict(family='Calibri', color='white', size=15))
#add Y axis details
fig.update_yaxes(
title_text = y_n,
title_font=dict(size=15, family='Verdana', color='white'),
tickfont=dict(family='Calibri', color='white', size=15))
#plot the line chart
fig.show()
#define neccesery values into the variables
population_sl = np.array(sl_summary['population'])[0]
vaccine_sl = np.array(sl_summary['people_vaccinated'])[0]
fully_vaccine_sl = np.array(sl_summary['people_fully_vaccinated'])[0]
cases_sl = np.array(sl_summary['total_cases'])[0]
deaths_sl = np.array(sl_summary['total_deaths'])[0]
#calculate Covid 19 Total Vaccination Daily Count
#define list for store proccessed values
c_list = []
p_list = []
diff_list = []
per_list = []
# calculate chanage presentage & value
for l , t in zip(range(0, (len(sl_df['people_vaccinated']) + 1)) , range(1, len(sl_df['people_vaccinated']))):
cu_value = sl_df['people_vaccinated'].iloc[t]
pr_value = sl_df['people_vaccinated'].iloc[l]
diff_val = cu_value - pr_value
per_val = round(( diff_val / pr_value) * 100,2)
c_list.append(cu_value)
p_list.append(pr_value)
diff_list.append(diff_val)
per_list.append(per_val)
# clean data for further calculations
date_dr = list(sl_df['date'].values)
per_list.insert(0,0)
diff_list.insert(0,0)
c_list.insert(0,0)
p_list.insert(0,0)
#create new dataframe
new_df = {'Date':date_dr ,'Current Faccination':c_list ,'Previous Faccination':p_list,'New Faccination' : diff_list, 'Change Rate' : per_list }
new_faccinations = pd.DataFrame(new_df,columns=['Date','Current Faccination','Previous Faccination','New Faccination','Change Rate'])
new_faccinations.tail()
"""# **Exploratory Data Analysis & Visualization - Sri Lanka**
## **Sri Lanka Covid 19 Vaccination Progress**
"""
#convert integer values to Millions format & round
def round_values(value_raw):
return round((value_raw/1000000),2)
#convert variable for do-nut chart
val_1 = [round_values(vaccine_sl), round_values(population_sl - vaccine_sl)]
val_2 = [round_values(fully_vaccine_sl), round_values(population_sl - fully_vaccine_sl)]
annoatation_text_1 = str(vaccine_sl)
annoatation_text_2 = str(fully_vaccine_sl)
labels_1 = ['Vaccinated(Millions)','Not Vaccinated(Millions)']
labels_2 = ['Fully Vaccinated(Millions)','Not Fully Vaccinated(Millions)']
title_name = "Sri Lanka Covid 19 Vaccination Progress " + str(Analysis_Date)
# Create subplots: use 'domain' type for Pie subplot
fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]], subplot_titles =( "Vaccine", "Fully Vaccine" ))
#add first pie-chart
fig.add_trace(go.Pie(labels=labels_1,
values= val_1,
name="Vaccination (at least 1 dose)",
marker=dict(colors=['#2d8cff','#727274'])),
1, 1)
#add first pie-chart
fig.add_trace(go.Pie(labels=labels_2,
values= val_2,
name="Fully Vaccination",
marker=dict(colors=['#ff00eb','#727274'])),
1, 2)
# use `hole` to create a donut-like pie chart
fig.update_traces(hole=.6,
hoverinfo="label+value",
hoverlabel=dict(font_size=20),
textfont_size=20,
showlegend=False)
# update other propertise
fig.update_layout(
title_text=title_name,
title_font_size = 25,
template='plotly_dark',
width = 1400,
height = 620,
# Add annotations in the center of the donut pies.
annotations=[dict(text='At Least 1 Dose <br>'+ annoatation_text_1, x=0.23, y=0.435, font_size=24, font_color='white' ,showarrow=False,),
dict(text='Fully Vaccination <br>'+annoatation_text_2, x=0.78, y=0.435, font_size=24, font_color='white',showarrow=False)])
fig.show()
"""## **Sri Lanka Covid 19 Tests Time Series**"""
dataset_line_chart = sl_df
x_line_chart = 'date'
y_line_chart = 'total_tests'
colour_line_chart = 'limegreen'
title_line_chart = 'Sri Lanka Covid 19 Tests Time Series'
xname_line_chart = 'Date'
yname_line_chart = 'Total Tests'
line_chart(dataset_line_chart, x_line_chart, y_line_chart, colour_line_chart, title_line_chart, xname_line_chart, yname_line_chart )
"""## **Covid 19 Daily Tests Count In Sri Lanka**"""
#covid 19 test daily count
dfr = sl_df
attnd = 'date'
attnc = 'new_tests'
mcn = 'red'
rcn = 'limegreen'
tn = 'Covid 19 Daily Tests In Sri Lanka'
yxn = 'Tests'
xxn = 'Date'
tmpn = 'plotly_dark'
customized_barchart(dfr, attnd, attnc, mcn, rcn, tn, yxn, xxn, tmpn)