Last active
June 6, 2020 05:13
-
-
Save rrealrangel/a5e6d87429a8197d3641d70011315086 to your computer and use it in GitHub Desktop.
Rutinas para generar archivos PNG con gráficos de la evolución de los casos diarios hospitalizados y ambulatorios de COVID-19 en México. Usa como fuente de información los archivos diarios de la base de datos de COVID-19 de la Secretaría de Salud (disponibles en https://bit.ly/3dE7ofg).
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 CASOS DIARIOS DE COVID-19 EN MEXICALI, B. C. | |
POR FECHA DE INGRESO A LA UNIDAD DE ATENCIÓN | |
Con cambios menores, este código puede ser usado para cualquier otro | |
municipio o estado de interés. | |
Created on Jun 05 00:54 2020 | |
@author: [email protected] | |
""" | |
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:/BLABLABLA' # Ruta completa al directorio que contiene los archivos diarios de la base de datos de COVID-19, disponible en https://bit.ly/3dE7ofg. | |
output_dir = 'C:/BLABLABLA' # Ruta completa al directorio donde se exportarán las gráficas 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' | |
} | |
for file in files: | |
# 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])) | |
df = pd.read_csv(file, encoding='latin') | |
df.index = df['ID_REGISTRO'] | |
df.drop(labels=['ID_REGISTRO'], axis=1, inplace=True) | |
amb = df.loc[ | |
(df['ENTIDAD_RES'] == 2) & # 2: Baja California | |
(df['MUNICIPIO_RES'] == 2) & # 2: Mexicali | |
(df['RESULTADO'] == 1) & # 1: Positivo | |
(df['TIPO_PACIENTE'] == 1) # 1: Ambulatorio | |
].groupby(df['FECHA_INGRESO']).count().iloc[:, 0] | |
amb.name = 'CASOS' | |
amb.index = pd.to_datetime(amb.index) | |
hos = df.loc[ | |
(df['ENTIDAD_RES'] == 2) & # 2: Baja California | |
(df['MUNICIPIO_RES'] == 2) & # 2: Mexicali | |
(df['RESULTADO'] == 1) & # 1: Positivo | |
(df['TIPO_PACIENTE'] == 2) # 2: Hospitalizado | |
].groupby(df['FECHA_INGRESO']).count().iloc[:, 0] | |
hos.name = 'CASOS' | |
hos.index = pd.to_datetime(hos.index) | |
new_index = pd.date_range( | |
start=min(min(amb.index), min(hos.index)), | |
end=max(max(amb.index), max(hos.index)), | |
freq='D' | |
) | |
amb = amb.reindex(index=new_index).fillna(0) | |
hos = hos.reindex(index=new_index).fillna(0) | |
hos_max_date = hos.idxmax() | |
hos_max = hos.max() | |
sum_max_date = (amb + hos).idxmax() | |
sum_max = (amb + hos).max() | |
# %% Figura | |
fig, ax = plt.subplots() | |
ax.set_title( | |
'Casos diarios de COVID-19 en Mexicali, B. C.\n' | |
'por fecha de ingreso a la unidad de atención\n' | |
'al {day} de {month} de 2020'.format(day=day, month=month), | |
fontsize=14 | |
) | |
xfrom = datetime.datetime( | |
year=2020, | |
month=3, | |
day=11 | |
) | |
xto = datetime.datetime( | |
year=2020, | |
month=6, | |
day=5 | |
) | |
ax.set_xlim(xfrom, xto) | |
ax.set_ylim(0, 130) | |
ax.bar( | |
x=hos.index, | |
height=hos, | |
color=[17/255, 138/255, 178/255], | |
width=1, | |
label='Hospitalizados' | |
) | |
def _xtext(this, other, thisy=0, othery=0): | |
if this < other: | |
return this - pd.to_timedelta(0.5, unit='days') | |
elif this > other: | |
return this + pd.to_timedelta(3.5, unit='days') | |
else: | |
if thisy < othery: | |
return this - pd.to_timedelta(0.5, unit='days') | |
else: | |
return this + pd.to_timedelta(3.5, unit='days') | |
def _ytext(date, threshold): | |
if date <= threshold: | |
return 96 | |
else: | |
return 125.5 | |
ax.annotate( | |
"Pico hospitalizados", | |
(hos_max_date, 120), | |
xytext=( | |
_xtext( | |
this=hos_max_date, | |
other=sum_max_date, | |
thisy=hos_max, | |
othery=sum_max | |
), | |
_ytext( | |
date=hos_max_date, | |
threshold=pd.to_datetime('2020-04-12') | |
)), | |
textcoords='data', | |
rotation=90, | |
ha='right', | |
va='top' | |
) | |
ax.annotate( | |
"Pico total", | |
(sum_max_date, 120), | |
xytext=( | |
_xtext( | |
this=sum_max_date, | |
other=hos_max_date, | |
thisy=sum_max, | |
othery=hos_max | |
), | |
_ytext( | |
date=sum_max_date, | |
threshold=pd.to_datetime('2020-04-12') | |
)), | |
textcoords='data', | |
rotation=90, | |
ha='right', | |
va='top' | |
) | |
ax.bar( | |
x=amb.index, | |
height=amb, | |
color=[6/255, 214/255, 160/255], | |
width=1, | |
label='Ambulatorios', | |
bottom=hos | |
) | |
ax.axvline( | |
x=hos_max_date, | |
color=[9/255, 69/255, 89/255], | |
linestyle='-.', | |
linewidth=1 | |
) | |
ax.axvline( | |
x=sum_max_date, | |
color=[3/255, 107/255, 80/255], | |
linestyle='-.', | |
linewidth=1 | |
) | |
myFmt = mdates.DateFormatter("%d-%m") | |
ax.xaxis.set_major_formatter(myFmt) | |
ax.legend(loc='upper left') | |
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(filedate), #format('05/06/20'), # | |
'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.12, | |
y=0.150 - (r * 0.025), | |
s=row, | |
ha='left', | |
fontdict=dict(size=5, color='gray'), | |
wrap=True | |
) | |
fig.subplots_adjust(bottom=0.25, top=0.80) | |
output_fname = ( | |
output_dir + | |
'/' + 'covid19_amb_hos_mxli_{year}{month}{day}.png'.format( | |
year=year, | |
month=monthn, | |
day=dayn | |
) | |
) | |
fig.savefig( | |
fname=output_fname, | |
dpi=400 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment