Update.
[python.git] / covid19.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import os, time, math
9 import numpy, csv
10 import matplotlib.pyplot as plt
11 import matplotlib.dates as mdates
12 import urllib.request
13
14 url = 'https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv'
15
16 file = 'time_series_19-covid-Confirmed.csv'
17
18 ######################################################################
19
20 if not os.path.isfile(file) or os.path.getmtime(file) < time.time() - 86400:
21     print('Retrieving file')
22     urllib.request.urlretrieve(url, file)
23
24 ######################################################################
25
26 with open(file, newline='') as csvfile:
27     reader = csv.reader(csvfile, delimiter=',')
28     times = []
29     nb_cases = {}
30     time_col = 5
31     for row_nb, row in enumerate(reader):
32         for col_nb, field in enumerate(row):
33             if row_nb >= 1 and col_nb == 1:
34                 country = field
35                 if not country in nb_cases:
36                     nb_cases[country] = numpy.zeros(len(times))
37             if row_nb == 0 and col_nb >= time_col:
38                 times.append(time.mktime(time.strptime(field, '%m/%d/%y')))
39             if row_nb == 1 and col_nb == time_col:
40                 nb_cases['World'] = numpy.zeros(len(times))
41             if row_nb >= 1:
42                 if col_nb >= time_col:
43                     nb_cases['World'][col_nb - time_col] += int(field)
44                     nb_cases[country][col_nb - time_col] += int(field)
45
46 ######################################################################
47
48 fig = plt.figure()
49 ax = fig.add_subplot(1, 1, 1)
50
51 ax.yaxis.grid(color='gray', linestyle='-', linewidth=0.25)
52 ax.set_title('Nb. of COVID-19 cases')
53 ax.set_xlabel('Date', labelpad = 10)
54 ax.set_yscale('log')
55
56 myFmt = mdates.DateFormatter('%b %d')
57 ax.xaxis.set_major_formatter(myFmt)
58 dates = mdates.epoch2num(times)
59
60 print('Countries:')
61 print(nb_cases.keys())
62
63 for key, color, label in [
64         ('World', 'blue', 'World'),
65         ('Switzerland', 'red', 'Switzerland'),
66         ('France', 'lightgreen', 'France'),
67         ('US', 'black', 'USA'),
68         ('Korea, South', 'gray', 'South Korea'),
69         ('Italy', 'purple', 'Italy'),
70         ('China', 'orange', 'China')
71 ]:
72     ax.plot(dates, nb_cases[key], color = color, label = label, linewidth=2)
73
74 ax.legend(frameon = False)
75
76 plt.show()
77 fig.savefig('covid19.png')
78
79 ######################################################################