Last active
June 9, 2020 06:00
-
-
Save rrealrangel/73de95a4f8088b832593937b9f7ef5e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
GENERAR FIGURAS DE LA EVOLUCIÓN DE DEFUNCIONES POR COVID-19 EN MÉXICO | |
Con cambios menores, este código puede ser usado para cualquier otro | |
municipio o estado de interés. | |
Created on Fri May 22 10:53:26 2020 | |
@author: r.realrangel@gmail.com | |
""" | |
from datetime import datetime as dt | |
from pathlib import Path | |
import datetime | |
import os | |
import pandas as pd | |
from matplotlib import dates as mdates | |
from matplotlib import pyplot as plt | |
source_dir = 'C:/' # Directorio que contiene los archivos CSV de la base de datos de COVID-19. | |
output_dir = 'C:/' # Directorio donde se guardarán las figuras en formato PNG. | |
files = sorted(list(Path(source_dir).glob(pattern='**/*.csv'))) | |
month_num = { | |
1: 'enero', 2: 'febrero', 3: 'marzo', 4: 'abril', 5: 'mayo', 6: 'junio', | |
7: 'julio', 8: 'agosto', 9: 'septiembre', 10: 'octubre', 11: 'noviembre', | |
12: 'diciembre' | |
} | |
month_num_abr = { | |
1: 'ene', 2: 'feb', 3: 'mar', 4: 'abr', 5: 'may', 6: 'jun', 7: 'jul', | |
8: 'ago', 9: 'sep', 10: 'oct', 11: 'nov', 12: 'dic' | |
} | |
for file in files[-1:]: | |
# Datos | |
dayn = file.stem[4:6] | |
day = str(int(dayn)) | |
monthn = file.stem[2:4] | |
month = month_num[int(monthn)] | |
year = '20' + str(int(file.stem[:2])) | |
db = pd.read_csv(file, encoding='latin') | |
db.index = pd.to_datetime(db['FECHA_SINTOMAS']) + pd.to_timedelta(1, 'd') | |
def_pos = db.loc[ | |
(db['ENTIDAD_RES'] == 2) & # 2: Baja California | |
(db['MUNICIPIO_RES'] == 2) & # 2: Mexicali | |
(db['FECHA_DEF'] != '9999-99-99') & | |
(db['RESULTADO'] == 1) # 1: Positivo | |
] | |
def_sos = db.loc[ | |
(db['ENTIDAD_RES'] == 2) & # 2: Baja California | |
(db['MUNICIPIO_RES'] == 2) & # 2: Mexicali | |
(db['FECHA_DEF'] != '9999-99-99') & | |
(db['RESULTADO'] == 3) # 3: Sospechoso | |
] | |
def_pos.index = pd.to_datetime(def_pos['FECHA_DEF']) | |
def_sos.index = pd.to_datetime(def_sos['FECHA_DEF']) | |
def_pos = def_pos['FECHA_DEF'].groupby(def_pos.index).count() | |
def_sos = def_sos['FECHA_DEF'].groupby(def_sos.index).count() | |
new_index = pd.date_range( | |
start=min(def_pos.index[0], def_sos.index[0]), | |
end=pd.to_datetime( | |
'-'.join([year, monthn, dayn]) | |
)) | |
def_pos = def_pos.reindex(new_index).fillna(0) | |
def_sos = def_sos.reindex(new_index).fillna(0) | |
defunc_accum = def_pos.cumsum() | |
# %% Plot | |
fig, ax = plt.subplots() | |
ax.set_title( | |
'Defunciones por COVID-19 en Mexicali, B. C.,\n' | |
'al {day} de {month} de 2020'.format( | |
day=day, | |
month=month | |
), | |
fontsize=14 | |
) | |
ax.bar( | |
x=def_pos.index, | |
height=def_pos, | |
color=[38/255, 38/255, 38/255], | |
width=1, | |
label='Defunciones (positivos)' | |
) | |
ax.bar( | |
x=def_sos.index, | |
height=def_sos, | |
color=[127/255, 127/255, 127/255], | |
width=1, | |
label='Defunciones (sospechosos)', | |
bottom=def_pos | |
) | |
ax2 = ax.twinx() | |
ax2.plot( | |
defunc_accum, | |
color=[239/255, 71/255, 111/255], | |
linewidth=2.5, | |
label='Defunciones acumuladas' | |
) | |
xfrom = datetime.datetime( | |
year=2020, | |
month=3, | |
day=11 | |
) | |
xto = datetime.datetime( | |
year=2020, | |
month=6, | |
day=8 | |
) | |
ax.set_xlim(xfrom, xto) | |
ax.grid(True) | |
ax.set_axisbelow(True) | |
ax.set_ylim(0, 25) | |
ax2.set_ylim(0, 500) | |
ax.set_xlabel('Fecha (dd-mm)') | |
ax.set_ylabel('Defunciones diarias') | |
ax2.set_ylabel('Defunciones acumuladas') | |
myFmt = mdates.DateFormatter("%d-%m") | |
ax.xaxis.set_major_formatter(myFmt) | |
fig.legend(loc=(0.125, 0.69)) | |
filedate = dt.utcfromtimestamp(os.path.getctime(file)).strftime( | |
'%d/%m/%Y' | |
) | |
disclaimer = [ | |
'La información presentada se proporciona en las condiciones en que se encuentra, sin que se asuma la obligación de ofrecer ningún tipo de garantía. El autor se', | |
'limita a proporcionar la información en los términos más precisos posibles derivada de la base de COVID-19, publicada por la Dirección General de Epidemiología', | |
'de la Secretaría de Salud, disponible en https://www.gob.mx/salud/documentos/datos-abiertos-152127 y consultados el {}. Así mismo, el autor no será'.format('08/06/20'), #format(filedate), # | |
'responsable de las posibles imprecisiones, errores u omisiones contenidos en dicha base de datos, así como daños directos, indirectos o riesgos financieros', | |
'asociados al uso de esta.' | |
] | |
for r, row in enumerate(disclaimer): | |
fig.text( | |
x=0.025, | |
y=0.125 - (r * 0.025), | |
s=row, | |
ha='left', | |
fontdict=dict(size=5, color='gray'), | |
wrap=True | |
) | |
fig.subplots_adjust(bottom=0.3) | |
output_fname = ( | |
output_dir + | |
'/' + 'covid19_defunciones_mxli_{year}{month}{day}.png'.format( | |
year=year, | |
month=monthn, | |
day=dayn | |
) | |
) | |
fig.savefig( | |
fname=output_fname, | |
dpi=400, | |
bbox_inches="tight" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment