Last active
June 20, 2020 06:15
-
-
Save rrealrangel/4c396cdfebb83f660c93fd5bcfceb768 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 CASOS DE COVID-19 EN MÉXICO. | |
Created on Fri May 22 10:53:26 2020 | |
@author: [email protected] | |
""" | |
from datetime import datetime as dt | |
from pathlib import Path | |
import datetime | |
import numpy as np | |
import os | |
import pandas as pd | |
from matplotlib import dates as mdates | |
from matplotlib import pyplot as plt | |
# %% Inputs | |
input_dir = 'RUTA/DEL/DIRECTORIO/CON/LOS/ARCHIVO/CSV/DE/LA/BASEDEDATOS/' # Disponibles en https://www.gob.mx/salud/documentos/datos-abiertos-152127. | |
input_files = sorted(list(Path(input_dir).glob(pattern='**/*.csv'))) | |
output_dir = 'RUTA/DEL/DIRECTORIO/DONDE/SE/GUARDARAN/LAS/FIGURAS/' | |
dbcat = 'RUTA/DEL/XLSX/DEL/CATALOGO/DE/CAMPOS/DE/LA/BASE/DE/DATOS/' #También disponible en https://www.gob.mx/salud/documentos/datos-abiertos-152127. | |
dbcat_municip = pd.read_excel( | |
io=dbcat, | |
sheet_name='Catálogo MUNICIPIOS', | |
index_col=[-1, 0] | |
) | |
dbcat_states = pd.read_excel( | |
io=dbcat, | |
sheet_name='Catálogo de ENTIDADES', | |
index_col=0 | |
) | |
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' | |
} | |
# %% Settings | |
region = {'state_numb': 2, 'munic_numb': 5} | |
region['state_name'] = dbcat_states.loc[ | |
region['state_numb'], 'ENTIDAD_FEDERATIVA' | |
].title() | |
region['munic_name'] = dbcat_municip.loc[ | |
(region['state_numb'], region['munic_numb']), 'MUNICIPIO' | |
].title() | |
for file in input_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']) | |
pos = db.loc[ | |
(db['ENTIDAD_RES'] == region['state_numb']) & | |
(db['MUNICIPIO_RES'] == region['munic_numb']) & | |
(db['RESULTADO'] == 1) # 1: Positivo | |
] | |
pos = pos.iloc[:, 0].groupby(by=pos.index).count() | |
pos.name = 'CASOS' | |
neg = db.loc[ | |
(db['ENTIDAD_RES'] == region['state_numb']) & | |
(db['MUNICIPIO_RES'] == region['munic_numb']) & | |
(db['RESULTADO'] == 2) # 2: Negativo | |
] | |
neg = neg.iloc[:, 0].groupby(by=neg.index).count() | |
neg.name = 'CASOS' | |
sos = db.loc[ | |
(db['ENTIDAD_RES'] == region['state_numb']) & | |
(db['MUNICIPIO_RES'] == region['munic_numb']) & | |
(db['RESULTADO'] == 3) # 3: Sospechoso | |
] | |
sos = sos.iloc[:, 0].groupby(by=sos.index).count() | |
sos.name = 'CASOS' | |
new_index = pd.date_range( | |
start=min(min(pos.index), min(sos.index)), | |
end=pd.to_datetime( | |
'-'.join([year, monthn, dayn]) | |
) | |
) | |
pos = pos.reindex(index=new_index).fillna(0) | |
neg = neg.reindex(index=new_index).fillna(0) | |
sos = sos.reindex(index=new_index).fillna(0) | |
sos_ratio = sos / (sos + pos + neg) | |
pos_accum = pos.cumsum() | |
possos_accum = (pos + sos).cumsum() | |
# %% Plot | |
fig, ax = plt.subplots() | |
ax.set_title( | |
'Casos de COVID-19 en {munic_name}, {state_name},\n' | |
'al {day} de {month} de 2020'.format( | |
munic_name=region['munic_name'], | |
state_name=region['state_name'], | |
day=day, | |
month=month | |
), | |
fontsize=14 | |
) | |
ax.bar( | |
x=pos.index, | |
height=pos, | |
color=[239/255, 71/255, 111/255], | |
width=1, | |
label='Confirmados' | |
) | |
ax.bar( | |
x=sos.index, | |
height=sos, | |
color=[255/255, 209/255, 102/255], | |
width=1, | |
label='Sospechosos', | |
bottom=np.nan_to_num(pos) | |
) | |
ax2 = ax.twinx() | |
ax2.plot( | |
pos_accum, | |
color=[50/255, 50/255, 50/255], | |
linewidth=2, | |
label='Confirmados acumulados' | |
) | |
ax2.annotate( | |
str(int(pos_accum[-1])), | |
(pos_accum.index[-1], pos_accum[-1]), | |
xytext=( | |
pos_accum.index[-1] - pd.Timedelta(value=12, unit='H'), | |
pos_accum[-1] + (pos_accum[-1] * 0.025) | |
), | |
textcoords='data', | |
ha='right', | |
va='bottom', | |
weight='bold' | |
) | |
xfrom = datetime.datetime(year=2020, month=3, day=11) | |
xto = datetime.datetime(year=2020, month=6, day=19) | |
ax.set_xlim(xfrom, xto) | |
ax.grid(True) | |
ax.set_axisbelow(True) | |
ax.set_ylim(0, None) | |
ax2.set_ylim(0, None) | |
ax.set_xlabel('Fecha de inicio de síntomas (dd-mm)') | |
ax.set_ylabel('Casos diarios') | |
ax2.set_ylabel('Confirmados acumulados') | |
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('19/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_casos_diarios_{state_numb}{munic_numb}_{year}{month}' | |
'{day}.png'.format( | |
state_numb=str(region['state_numb']).zfill(2), | |
munic_numb=str(region['munic_numb']).zfill(3), | |
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