This repository has been archived by the owner on Dec 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
plot.py
executable file
·1666 lines (1377 loc) · 52.4 KB
/
plot.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 argparse
import math
import os
from datetime import datetime as dt, timedelta
from operator import add
import matplotlib
import matplotlib.font_manager as font_manager
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
# import mpld3
import numpy as np
import pandas as pd
from matplotlib.dates import DateFormatter as df
from matplotlib.dates import MonthLocator
from tqdm.rich import tqdm
from getData import getData
from readData import readData
from processData import processData
from tidySVG import tidySVG
def mainPlot(t, dataDir="data/", plotsDir="plots/", avg=True):
"""avg indicates seven day average of new cases should be used"""
nationList = [["UK"], ["Scotland", "England", "Northern Ireland", "Wales"]]
colorsList = [["#2271d3"], ["#003078", "#5694CA", "#FFDD00", "#D4351C"]]
fignames = ["", "-Nation"]
for outerI, nations in enumerate(nationList):
data = {}
for nation in nations:
if avg:
data[nation] = pd.read_csv(
dataDir + nation + ".avg.csv", index_col=0, parse_dates=True
)
else:
data[nation] = pd.read_csv(
dataDir + nation + ".csv", index_col=0, parse_dates=True
)
suffix = fignames[outerI]
testingPlot(suffix, outerI, avg, t, data, nations, plotsDir)
percentPositivePlot(
t, plotsDir, avg, colorsList[outerI], suffix, outerI, nations, data,
)
doubleBarChartPlot(t, plotsDir, avg, suffix, outerI, nations, data)
mortalityHospitalisationPlot(
suffix, outerI, avg, t, data, colorsList[outerI], nations, plotsDir,
)
deathsPlot(suffix, outerI, avg, t, data, nations, plotsDir, dataDir)
if avg == False:
weeklyIncreasePlot(data, nations, suffix, outerI, t, plotsDir)
if outerI == 0:
ComparisonUK(plotsDir, avg, t, data)
else:
ComparisonNation(plotsDir, avg, t, data, nations)
def readFile(name, avg):
data = readData(name)
# convert to np array and separate dates from case counts
casesData = np.array(data)
casesRawDates = casesData[:, 0]
casesDates = [dt.strptime(x, "%Y-%m-%d") for x in casesRawDates]
cases = casesData[:, 1].astype(float)
# compute seven day average of cases if enabled
if avg:
cases = n_day_avg(cases, 7)
return cases, casesDates
def testingPlot(suffix, outerI, avg, t, data, nations, plotsDir):
figname = "Testing" + suffix
title = "positive test rate of COVID-19 in the UK"
if avg:
figname += "-Avg"
title = "average " + title
updateProgressBar(figname, t)
if outerI == 0:
fig, ax = plt.subplots()
setTitle(ax, title)
ax.plot(data["UK"].index, data["UK"]["posTests"], color="#333")
maxArray = [x >= 5 for x in data["UK"]["posTests"]]
minArray = [x <= 5 for x in data["UK"]["posTests"]]
ax.fill_between(
data["UK"].index,
5,
data["UK"]["posTests"].fillna(0),
where=maxArray,
facecolor="#FF41367F",
interpolate=True,
)
ax.fill_between(
data["UK"].index,
5,
data["UK"]["posTests"].fillna(0),
where=minArray,
facecolor="#3D99707F",
interpolate=True,
)
lockdownVlines(ax)
dateAxis(ax)
ax.set_xlabel(
"""
Note: Target positive testing rate is 5% according to the World Health Organization.""",
color="#666",
)
setYLabel(ax, "Percent positive tests per day", avg)
percentAxis(ax)
removeSpines(ax)
showGrid(ax)
else:
fig, axs = plt.subplots(2, 2, sharex=True)
axs = axs.flatten()
setSupTitle(fig, title)
for j, nation in enumerate(data):
ax = axs[j]
ax.plot(data[nation].index, data[nation]["posTests"], color="#333")
maxArray = [x >= 5 for x in data[nation]["posTests"]]
minArray = [x <= 5 for x in data[nation]["posTests"]]
ax.fill_between(
data[nation].index,
5,
data[nation]["posTests"].fillna(0),
where=maxArray,
facecolor="#FF41367F",
interpolate=True,
)
ax.fill_between(
data[nation].index,
5,
data[nation]["posTests"].fillna(0),
where=minArray,
facecolor="#3D99707F",
interpolate=True,
)
dateAxis(ax)
reduceXlabels(ax)
reduceYlabels(ax)
setYLabel(ax, "% positive tests per day", avg)
showGrid(ax)
percentAxis(ax)
ax.set_title(nations[j])
removeSpines(ax)
savePlot(plotsDir, figname, fig)
def percentPositivePlot(t, plotsDir, avg, colors, suffix, outerI, nations, data):
fig, ax = plt.subplots()
figname = "PercentPositive" + suffix
if outerI == 0:
title = "UK COVID-19 cases compared to percentage of tests which are positive"
else:
title = "percentage of tests which are positive for COVID-19 in UK nations"
if avg:
figname += "-Avg"
title = "Average " + title
updateProgressBar(figname, t)
setTitle(ax, title)
if outerI == 0:
ax.bar(data["UK"].index, data["UK"]["reportedCases"], color="orangered")
setYLabel(ax, "Daily COVID-19 Cases in the UK", avg, color="orangered")
ax2 = ax.twinx()
ax2.plot_date(data["UK"].index, data["UK"]["posTests"], "white", linewidth=3)
ax2.plot_date(
data["UK"].index, data["UK"]["posTests"], "#333", linewidth=2,
)
setYLabel(ax2, "Percent positive tests per day", avg, ax2=True)
ax.spines["top"].set_visible(False)
ax2.spines["top"].set_visible(False)
threeFigureAxis(ax)
percentAxis(ax2)
ax2.axline(
(0, 5),
slope=0,
ls="dotted",
color="black",
label="WHO 5% reopening threshold",
)
lockdownVlines(ax2)
elif outerI == 1:
for i, nation in enumerate(data):
nationTests = data[nation]["posTests"]
ax.plot_date(
data[nation].index,
nationTests,
colors[i],
linewidth=2,
label=nations[i],
)
ax.axline(
(0, 5),
slope=0,
ls="dotted",
color="black",
label="WHO 5% reopening threshold",
)
setYLabel(ax, "Percent positive tests per day", avg)
percentAxis(ax)
showGrid(ax)
ax.set_xlabel(
"""
Note: Positive rates should be at or below 5 percent for at least 14 days before
a country can safely reopen, according to the World Health Organization.""",
color="#666",
)
dateAxis(ax)
plt.legend()
removeSpines(ax)
savePlot(plotsDir, figname, fig)
def doubleBarChartPlot(t, plotsDir, avg, suffix, outerI, nations, data):
figname = "DoubleBarChart" + suffix
title = "Number of tests vs positive tests"
if avg:
figname += "-Avg"
title += " (averaged)"
updateProgressBar(figname, t)
if outerI == 0:
fig, ax = plt.subplots()
ax.set_title(title, fontweight="bold")
fivePercent = [x * 0.05 for x in data["UK"]["reportedTests"]]
ax.bar(
data["UK"].index,
data["UK"]["reportedTests"],
color="#2271d3",
label="Total tests",
)
ax.bar(
data["UK"].index,
fivePercent,
color="black",
label="WHO 5% reopening threshold",
)
ax.bar(
data["UK"].index,
data["UK"]["reportedCases"],
color="orangered",
label="Positive tests",
)
lockdownVlines(ax)
dateAxis(ax)
ax.set_xlabel(
"""
Note: Positive rates should be at or below 5 percent for at least 14 days before
a country can safely reopen, according to the World Health Organization.""",
color="#666",
)
setYLabel(ax, "Number of tests per day", avg)
threeFigureAxis(ax)
removeSpines(ax)
showGrid(ax)
ax.legend()
else:
fig, axs = plt.subplots(2, 2, sharex=True)
axs = axs.flatten()
fig.suptitle(title, fontweight="bold")
for j, nation in enumerate(data):
ax = axs[j]
tests = data[nation]["reportedTests"]
fivePercent = [x * 0.05 for x in tests]
ax.bar(
data[nation].index, tests, color="#2271d3", label="Total tests",
)
ax.bar(
data[nation].index,
fivePercent,
color="black",
label="WHO 5% reopening threshold",
)
ax.bar(
data[nation].index,
data[nation]["reportedCases"],
color="orangered",
label="Positive tests",
)
dateAxis(ax)
reduceXlabels(ax)
reduceYlabels(ax)
setYLabel(ax, "Number of tests per day", avg)
ax.set_title(nations[j])
threeFigureAxis(ax)
removeSpines(ax)
showGrid(ax)
savePlot(plotsDir, figname, fig)
def mortalityHospitalisationPlot(
suffix, outerI, avg, t, data, colors, nations, plotsDir
):
innerFignames = ["Mortality", "Hospitalisation"]
innerTitles = ["Mortality", "Hospitalisation rate"]
innerYs = ["deathDates", "hospitalisationDates"]
innerXs = ["mortality", "hospitalisationRate"]
innerYlables = ["mortality", "hospitalisation rate"]
innerNotes = [
"Mortality is calculated as deaths",
"Hospitalisation rate is calculated as hospitalisations",
]
innerColors = ["black", "#851bc2"]
for innerI in range(len(innerFignames)):
figname = innerFignames[innerI] + suffix
if avg:
figname += "-Avg"
updateProgressBar(figname, t)
fig, ax = plt.subplots()
if outerI == 0:
title = "%s of COVID-19 in the UK" % innerTitles[innerI]
ax.bar(data["UK"].index, data["UK"]["reportedCases"], color="orangered")
setYLabel(ax, "Daily COVID-19 Cases in the UK", avg, color="orangered")
ax2 = ax.twinx()
ax2.plot_date(
data["UK"].index, data["UK"][innerXs[innerI]], "white", linewidth=3,
)
ax2.plot_date(
data["UK"].index,
data["UK"][innerXs[innerI]],
innerColors[innerI],
linewidth=2,
)
yLabel = "Percent %s per day" % innerYlables[innerI]
setYLabel(ax2, yLabel, avg, color=innerColors[innerI], ax2=True)
ax.spines["top"].set_visible(False)
ax2.spines["top"].set_visible(False)
threeFigureAxis(ax)
percentAxis(ax2)
elif outerI == 1:
title = "%s of COVID-19 in UK nations" % innerTitles[innerI]
for i, nation in enumerate(data):
nationDeaths = data[nation][innerXs[innerI]]
ax.plot_date(
data[nation].index,
nationDeaths,
colors[i],
linewidth=2,
label=nations[i],
)
setYLabel(ax, "Percent %s per day" % innerYlables[innerI], avg)
percentAxis(ax)
plt.legend()
if avg:
title += " (averaged)"
ax.set_title(title, fontweight="bold")
xLabel = (
"\nNote: %s per day divided by the sum of cases in the prior 28 days"
% innerNotes[innerI]
)
if innerI == 1 and outerI == 1:
xLabel += "\nWales includes suspected COVID-19 patients in hospitalisation figures while the other nations include only confirmed cases."
ax.set_xlabel(xLabel, color="#666")
dateAxis(ax)
removeSpines(ax)
savePlot(plotsDir, figname, fig)
def deathsPlot(suffix, outerI, avg, t, data, nations, plotsDir, dataDir):
figname = "Deaths" + suffix
title = "Comparing four different death metrics in the UK for COVID-19"
if avg:
figname += "-Avg"
title = "average " + title
updateProgressBar(figname, t)
if outerI == 0:
fig, ax = plt.subplots()
setTitle(ax, title)
excessDeaths = readData(dataDir + "UK.deaths.excess.csv", type="dict")
excessSeries = pd.Series(excessDeaths)
ax.fill_between(
excessSeries.index,
0,
excessSeries,
facecolor="#f4f4f4",
interpolate=True,
label="Excess deaths"
)
ax.plot(
excessSeries.index,
excessSeries,
color="#f4f4f4",
)
ax.plot(
data["UK"].index,
data["UK"]["reportedDeaths"],
color="#bebebe",
label="Deaths by reported date",
)
ax.plot(
data["UK"].index,
data["UK"]["specimenDeaths"],
color="#6a6a6a",
label="Deaths by date of death",
)
ax.plot(
data["UK"].index,
data["UK"]["certificateDeaths"],
color="#000",
label="Death certificates with COVID-19 as a cause",
)
dateAxis(ax)
setYLabel(ax, "Deaths per day", avg)
threeFigureAxis(ax, bottom=None)
plt.legend()
removeSpines(ax)
showGrid(ax)
else:
fig, axs = plt.subplots(2, 2, sharex=True)
axs = axs.flatten()
setSupTitle(fig, title)
for j, nation in enumerate(data):
ax = axs[j]
excessDeaths = readData(dataDir + nation + ".deaths.excess.csv", type="dict")
excessSeries = pd.Series(excessDeaths)
ax.fill_between(
excessSeries.index,
0,
excessSeries,
facecolor="#f4f4f4",
interpolate=True,
label="Excess deaths"
)
ax.plot(
excessSeries.index,
excessSeries,
color="#f4f4f4",
)
ax.plot(
data[nation].index,
data[nation]["reportedDeaths"],
color="#DFDFDF",
label="Reported deaths",
)
ax.plot(
data[nation].index,
data[nation]["specimenDeaths"],
color="#6C6C6C",
label="Deaths by date of death",
)
ax.plot(
data[nation].index,
data[nation]["certificateDeaths"],
color="#000",
label="Death certificates",
)
dateAxis(ax)
reduceXlabels(ax)
reduceYlabels(ax)
if j == 0:
plt.legend()
setYLabel(ax, "deaths per day", avg)
showGrid(ax)
threeFigureAxis(ax)
ax.set_title(nations[j])
removeSpines(ax)
savePlot(plotsDir, figname, fig)
def weeklyIncreasePlot(data, nations, suffix, outerI, t, plotsDir="plots/"):
if outerI == 0:
df = data[nations[0]]
grouped = df.resample("W").sum()
types = [
{
"title": "reported cases",
"figname": "-Cases-Reported",
"col": "reportedCases",
},
{"title": "cases", "figname": "-Cases-Specimen", "col": "specimenCases",},
{
"title": "reported deaths",
"figname": "-Deaths-Reported",
"col": "reportedDeaths",
},
{
"title": "deaths",
"figname": "-Deaths-Specimen",
"col": "specimenDeaths",
},
{
"title": "patients in hospital",
"figname": "-inHospital",
"col": "inHospital",
},
]
for figtype in types:
figname = "Increase" + suffix + figtype["figname"]
title = "weekly increase of COVID-19 %s in the UK" % figtype["title"]
updateProgressBar(figname, t)
lastSunday = df[figtype["col"]].last_valid_index() - timedelta(
df[figtype["col"]].last_valid_index().isoweekday()
)
plotData = grouped[grouped[figtype["col"]].gt(1000).idxmax() : lastSunday][
figtype["col"]
].pct_change()
positive = plotData <= 0
fig, ax = plt.subplots()
setTitle(ax, title)
ax.bar(
plotData.index,
plotData,
color=positive.map({True: "#9ECCB8", False: "#FFA09B"}),
width=5.6,
)
lockdownVlines(ax)
dateAxis(ax)
setYLabel(ax, "Weekly increase in COVID-19 %s" % figtype["title"], 0)
percentAxis(ax, setBottom=0)
removeSpines(ax)
showGrid(ax)
savePlot(plotsDir, figname, fig)
else:
pass
def ComparisonUK(plotsDir, avg, t, data):
figname = "Comparison"
title = "Comparing daily COVID-19 cases, hospitalisation and deaths in the UK"
if avg:
figname += "-Avg"
updateProgressBar(figname, t)
fig, ax = plt.subplots()
fig.subplots_adjust(right=0.75)
ax2 = ax.twinx()
ax3 = ax.twinx()
axes = [ax, ax2, ax3]
# Offset the right spine of par2.
ax3.spines["right"].set_position(("axes", 1.15))
# Second, show the right spine.
ax3.spines["right"].set_visible(True)
(p1,) = ax.plot(
data["UK"].index,
data["UK"]["reportedCases"],
"orangered",
ls="-",
label="Cases",
)
(p2,) = ax2.plot(
data["UK"].index,
data["UK"]["inHospital"],
"#851bc2",
ls="-",
label="Patients in hospital",
)
(p3,) = ax3.plot(
data["UK"].index, data["UK"]["specimenDeaths"], "#333", ls="-", label="Deaths",
)
setYLabel(ax, "Cases", avg)
setYLabel(ax2, "Hospitalisations", avg)
setYLabel(ax3, "Deaths", avg)
ax.yaxis.label.set_color(p1.get_color())
ax2.yaxis.label.set_color(p2.get_color())
if avg:
title += " (averaged)"
ax.set_title(title, fontweight="bold")
dateAxis(ax)
for axis in axes:
threeFigureAxis(axis)
lines = [p1, p2, p3]
ax.legend(lines, [l.get_label() for l in lines], loc="upper center")
ax.spines["top"].set_visible(False)
ax2.spines["top"].set_visible(False)
removeSpines(ax3, all=True)
ax3.spines["right"].set_visible(True)
savePlot(plotsDir, figname, fig)
def ComparisonNation(plotsDir, avg, t, data, nations):
populations = [5466000, 56550138, 1895510, 3169586]
fignameSuffix = ["", "-Per-Capita"]
titleSuffix = ["", ", per capita"]
perCapita = [0, 1]
for i in range(2):
figname = "Comparison-Nation" + fignameSuffix[i]
title = (
"Comparing daily COVID-19 cases, hospitalisation and deaths in the UK nations"
+ titleSuffix[i]
)
if avg:
figname += "-Avg"
updateProgressBar(figname, t)
fig, axs = plt.subplots(2, 2, sharex=True)
fig.subplots_adjust(right=0.75, wspace=0.4)
if avg:
title += " (averaged)"
fig.suptitle(title, fontweight="bold")
axs = axs.flatten()
primary_ax = []
secondary_ax = []
tertiary_ax = []
axMax = [0, 0, 0]
for j, nation in enumerate(data):
ax = axs[j]
ax2 = ax.twinx()
ax3 = ax.twinx()
axes = [ax, ax2, ax3]
# Offset the right spine of par2.
ax3.spines["right"].set_position(("axes", 1.15))
# Second, show the right spine.
ax3.spines["right"].set_visible(True)
cases = data[nation]["reportedCases"]
inHospital = data[nation]["inHospital"]
deaths = data[nation]["specimenDeaths"]
if perCapita[i]:
cases = [x / populations[j] * 100 for x in cases]
inHospital = [x / populations[j] * 100 for x in inHospital]
deaths = [x / populations[j] * 100 for x in deaths]
(p1,) = ax.plot(data[nation].index, cases, "orangered", ls="-")
(p2,) = ax2.plot(data[nation].index, inHospital, "#851bc2", ls="-",)
ax3.plot(data[nation].index, deaths, "#333", ls="-")
setYLabel(ax, "Cases", avg)
setYLabel(ax2, "Patients in hospital", avg)
setYLabel(ax3, "Deaths", avg)
ax.yaxis.label.set_color(p1.get_color())
ax2.yaxis.label.set_color(p2.get_color())
ax.set_title(title, fontweight="bold")
dateAxis(ax)
reduceXlabels(ax)
for axis in axes:
if perCapita[i]:
percentAxis(axis)
else:
threeFigureAxis(axis)
axis.yaxis.set_major_locator(plt.MaxNLocator(3))
ax.spines["top"].set_visible(False)
ax2.spines["top"].set_visible(False)
removeSpines(ax3, all=True)
ax3.spines["right"].set_visible(True)
if perCapita[i]:
primary_ax.append(ax)
secondary_ax.append(ax2)
tertiary_ax.append(ax3)
if j > 0:
ax.tick_params(labelleft=False)
ax2.tick_params(labelright=False)
ax3.tick_params(labelright=False)
for k, axis in enumerate(axes):
_, ymax = axis.get_ylim()
if ymax > axMax[k]:
axMax[k] = ymax
ax.set_title(nations[j])
removeSpines(ax)
if perCapita[i]:
for axis in primary_ax:
axis.set_ylim(top=axMax[0])
for axis in secondary_ax:
axis.set_ylim(top=axMax[1])
for axis in tertiary_ax:
axis.set_ylim(top=axMax[2])
plt.annotate(
"Note: Wales includes suspected COVID-19 patients in hospitalisation figures while the other nations include only confirmed cases.",
xy=(0.25, 0.025),
xycoords="figure fraction",
color="#666",
)
savePlot(plotsDir, figname, fig, size=(24, 12))
def lockdownVlines(ax):
nationLockdownDates = [dt(2020, 3, 23), dt(2020, 11, 5), dt(2020, 12, 20)]
nationLockdownEasing = [dt(2020, 7, 4), dt(2020, 12, 2), dt(2021, 7, 19)]
ymin, ymax = ax.get_ylim()
for i, (x1, x2) in enumerate(zip(nationLockdownDates, nationLockdownEasing)):
ax.axvspan(
x1,
x2,
alpha=0.15,
color="#777",
label="Lockdown" if i == 0 else "",
zorder=0.99,
)
ax.vlines(
x=dt(2020, 3, 11),
ymin=ymin,
ymax=ymax,
color="#333",
ls="dashed",
label="WHO declares pandemic",
)
plt.legend()
def nationPlot(t, dataDir="data/", plotsDir="plots/", avg=True):
data = [
{"name": "England", "color": "#5694CA", "population": 56550138},
{"name": "Northern Ireland", "color": "#FFDD00", "population": 1895510},
{"name": "Scotland", "color": "#003078", "population": 5466000},
{"name": "Wales", "color": "#D4351C", "population": 3169586},
]
totalPopulation = sum([x["population"] for x in data])
types = [
{
"fileName": ".cases.reported",
"figname": "Nation-Cases-Reported",
"title": "COVID-19 cases by date reported",
"yLabel": "tested positive",
},
{
"fileName": ".deaths.reported",
"figname": "Nation-Deaths-Reported",
"title": "deaths within 4 weeks of a positive COVID-19 test by date reported",
"yLabel": "who have died within 28 days of a positive test",
},
{
"fileName": ".cases",
"figname": "Nation-Cases",
"title": "COVID-19 cases in UK Nations",
"yLabel": "tested positive",
},
{
"fileName": ".deaths",
"figname": "Nation-Deaths",
"title": "deaths within 4 weeks of a positive COVID-19 test",
"yLabel": "who have died within 28 days of a positive test",
},
{
"fileName": ".inHospital",
"figname": "Nation-inHospital",
"title": "patients in hospital with COVID-19",
"yLabel": "Patients in hospital with COVID-19",
},
{
"fileName": ".inVentilationBeds",
"figname": "Nation-Ventilation",
"title": "COVID-19 patients in mechanical ventilation beds by nation",
"yLabel": "who are in mechanical ventilation beds",
},
{
"fileName": ".vaccinations.weekly",
"figname": "Nation-Vaccinations",
"title": "COVID-19 vaccinations by nation",
"yLabel": "who have received vaccinations",
},
]
iterations = len(types)
if avg:
iterations = len(types) - 1
for figType in range(iterations):
series = []
for i, nation in enumerate(data):
fileName = dataDir + nation["name"] + types[figType]["fileName"] + ".csv"
if figType == 2 or figType == 3:
nationData = readData(fileName, type="dict", skip=5)
else:
nationData = readData(fileName, type="dict")
nationSeries = pd.Series(nationData, name=nation["name"])
if avg:
nationAvgSeries = pd.Series(
n_day_avg(nationSeries),
index=nationSeries.index,
name=nation["name"],
)
series.append(nationAvgSeries)
else:
series.append(nationSeries)
df = pd.concat(series, axis=1)
dates = df.index
fignameSuffix = ["", "-Per-Capita"]
titleSuffix = ["", ", per capita"]
perCapita = [0, 1]
barWidth = 0.8
alignment = "center"
if figType == len(types) - 1:
barWidth = -5.6
alignment = "edge"
for i in range(len(fignameSuffix)):
figname = types[figType]["figname"] + fignameSuffix[i]
if avg:
figname += "-Avg"
title = "Average " + types[figType]["title"] + titleSuffix[i]
else:
title = types[figType]["title"] + titleSuffix[i]
updateProgressBar(figname, t)
fig, ax = plt.subplots()
setTitle(ax, title)
bottom = [0] * len(df.index)
for nation in data:
plotData = df[nation["name"]]
if perCapita[i]:
plotData = [x / nation["population"] * 100 for x in plotData]
ax.plot(
dates,
plotData,
color=nation["color"],
label=nation["name"],
linewidth=2,
)
else:
ax.bar(
dates,
plotData,
color=nation["color"],
label=nation["name"],
bottom=bottom,
width=barWidth,
align=alignment,
)
bottom = list(map(add, plotData.fillna(0), bottom))
if not perCapita[i]:
lockdownVlines(ax)
dateAxis(ax)
if figType == len(types) - 1:
dateAxis(ax, left=dt(2020, 12, 1))
handles, labels = ax.get_legend_handles_labels()
ax.legend(reversed(handles), reversed(labels))
if perCapita[i]:
yLabel = "Percent of nation " + types[figType]["yLabel"]
else:
yLabel = types[figType]["title"]
setYLabel(ax, yLabel, avg)
if perCapita[i]:
percentAxis(ax)
else:
threeFigureAxis(ax)
removeSpines(ax)
showGrid(ax)
savePlot(plotsDir, figname, fig)
if figType not in [4, 5]:
# Cumulative
yLabels = ["UK population", "nation"]
if not avg:
for i in range(len(yLabels)):
figname = (
types[figType]["figname"] + "-Cumulative" + fignameSuffix[i]
)
updateProgressBar(figname, t)
fig, ax = plt.subplots()
ax.set_title(
"Cumulative %s%s" % (types[figType]["title"], titleSuffix[i]),
fontweight="bold",
)
bottom = [0] * len(df.index)
for nation in data:
reportedData = df[nation["name"]].fillna(0)
if perCapita[i]:
reportedData = [
x / nation["population"] * 100 for x in reportedData
]
else:
reportedData = [
x / totalPopulation * 100 for x in reportedData
]
reportedData = np.cumsum(reportedData)
if perCapita[i]:
ax.plot(
dates,
reportedData,
color=nation["color"],
label=nation["name"],
linewidth=2,
)
else:
ax.bar(
dates,
reportedData,
color=nation["color"],
label=nation["name"],
bottom=bottom,
width=barWidth,
align=alignment,
)