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
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 = url[url.rfind('/')+1:]
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:
40                 if col_nb >= time_col:
41                     nb_cases[country][col_nb - time_col] += int(field)
42
43 countries = list(nb_cases.keys())
44 countries.sort()
45 print('Countries: ', countries)
46
47 nb_cases['World'] = sum(nb_cases.values())
48
49 ######################################################################
50
51 fig = plt.figure()
52 ax = fig.add_subplot(1, 1, 1)
53
54 ax.yaxis.grid(color='gray', linestyle='-', linewidth=0.25)
55 ax.set_title('Nb. of COVID-19 cases')
56 ax.set_xlabel('Date', labelpad = 10)
57 ax.set_yscale('log')
58
59 myFmt = mdates.DateFormatter('%b %d')
60
61 ax.xaxis.set_major_formatter(myFmt)
62 dates = mdates.epoch2num(times)
63
64 for key, color, label in [
65         ('World', 'blue', 'World'),
66         ('Switzerland', 'red', 'Switzerland'),
67         ('France', 'lightgreen', 'France'),
68         ('US', 'black', 'USA'),
69         ('Korea, South', 'gray', 'South Korea'),
70         ('Italy', 'purple', 'Italy'),
71         ('China', 'orange', 'China')
72 ]:
73     ax.plot(dates, nb_cases[key], color = color, label = label, linewidth=2)
74
75 ax.legend(frameon = False)
76
77 plt.show()
78
79 fig.savefig('covid19.png')
80
81 ######################################################################