Skip to content

Instantly share code, notes, and snippets.

@rrealrangel
Last active July 15, 2020 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrealrangel/0c73890e8967967e0e17f5021ee825f3 to your computer and use it in GitHub Desktop.
Save rrealrangel/0c73890e8967967e0e17f5021ee825f3 to your computer and use it in GitHub Desktop.
# -*- 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: r.realrangel@gmail.com
"""
from pathlib import Path
import datetime
import pandas as pd
from matplotlib import dates as mdates
from matplotlib import pyplot as plt
# %% Inputs
input_dir = 'C:/' # Directorio que contiene los archivos CSV de la base de datos de COVID-19.
input_files = sorted(list(Path(input_dir).glob(pattern='**/*.csv')))
output_dir = 'C:/' # Directorio donde se guardarán las figuras en formato PNG.
dbcat = 'C:/' # Ruta completa del archivo Catalogos_0412.xlsx de la base de datos de COVID-19
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
aux_pos = {}
aux_posysos = {}
municipios = range(1, 6)
for munic_numb in municipios:
region = {'state_numb': 2, 'munic_numb': munic_numb}
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()
# %% Get the data
file = 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'
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)
sos = sos.reindex(index=new_index).fillna(0)
aux_pos[region['munic_name']] = pos
aux_posysos[region['munic_name']] = sos + pos
pos = pd.DataFrame(aux_pos)
posysos = pd.DataFrame(aux_posysos)
pos_ma = pos.rolling(window=5, center=True).mean().loc['2020-03-01':]
posysos_ma = posysos.rolling(window=5, center=True).mean().loc['2020-03-01':]
poblacion = {
'Ensenada': 466814,
'Mexicali': 936826,
'Tecate': 101079,
'Playas de Rosarito': 90668
}
# %% Plot
plt.rcParams["figure.figsize"] = (3.9370, 5.9055)
fig, ax = plt.subplots(len(municipios), 1)
figure_title = (
'COVID-19 en los municipios de\n'
'Baja California,\n'
'al {} de {} de {}'.format(day, month, year)
)
ax[0].set_title(
label=figure_title,
fontsize=14
)
for m, munic in enumerate(pos_ma.columns):
ax[m].grid(b=True)
ax[m].set_axisbelow(True)
ax[m].text(
x=0.01,
y=0.8,
s=munic,
transform=ax[m].transAxes
)
# Casos confirmados.
x = pos_ma.loc[
:dt.datetime(year=int(year), month=int(monthn), day=int(dayn)) -
dt.timedelta(days=14)
].index
y = pos_ma[munic].loc[
:dt.datetime(year=int(year), month=int(monthn), day=int(dayn)) -
dt.timedelta(days=14)
]
ax[m].plot(
x, y, color=[239/255, 71/255, 111/255], lw=3, label='Confirmados',
zorder=3
)
# Casos confirmados + casos sospechosos
x = posysos_ma.loc[
:dt.datetime(year=int(year), month=int(monthn), day=int(dayn)) -
dt.timedelta(days=7)
].index
y = posysos_ma[munic].loc[
:dt.datetime(year=int(year), month=int(monthn), day=int(dayn)) -
dt.timedelta(days=7)
]
ax[m].plot(
x, y, color=[255/255, 209/255, 102/255], lw=3, zorder=2,
label='Confirmados + sospechosos'
)
# Jornada Nacional de Sana Distancia.
jnsd_i = dt.datetime(year=2020, month=3, day=23)
jnsd_f = dt.datetime(year=2020, month=6, day=1)
ax[m].axvspan(
xmin=jnsd_i, xmax=jnsd_f, color='0.9', zorder=-1,
label='Jornada Nacional de Sana Distancia'
)
# Formato de los ejes.
ax[m].set_xlim(
dt.datetime(year=2020, month=3, day=1),
dt.datetime(year=int(year), month=int(monthn), day=int(dayn))
)
myFmt = mdates.DateFormatter("%d-%m")
ax[m].xaxis.set_major_formatter(myFmt)
ax[m].xaxis.set_ticks(
pd.date_range(
start=dt.datetime(
year=2020, month=3, day=1
),
end=dt.datetime(
year=int(year), month=int(monthn), day=int(dayn)
),
freq='MS'
)
)
ax[m].set_yticks([0, np.ceil(posysos_ma.max(axis=0)[munic])])
ax[m].set_yticklabels([0, int(np.ceil(posysos_ma.max(axis=0)[munic]))])
if m < 4:
ax[m].tick_params(
# axis='y', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
left=True,
labelbottom=False, # labels along the bottom edge are off
labelleft=True)
else:
ax[m].tick_params(
# axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=True, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
left=True,
labelbottom=True, # labels along the bottom edge are off
labelleft=True)
ax[m].set_xlabel('Fecha de inicio de síntomas (dd-mm)')
ax[2].set_ylabel('Nuevos casos diarios')
ax[m].legend(loc=(0.01, -1.44), frameon=False)
disclaimer = [
'La información presentada se proporciona en las condiciones en que se '
'encuentra, sin que se\nasumala obligación de ofrecer ningún tipo de '
'garantía. El autor se limita a proporcionar la\ninformación en los '
'términos más precisos posibles derivada de la base de COVID-19, '
'publicada\npor la Dirección General de Epidemiología de la Secretaría de '
'Salud, disponible en\n'
'https://www.gob.mx/salud/documentos/datos-abiertos-152127 y '
'consultados el 14/07/20. Así\nmismo, el autor no será responsable de '
'las posibles imprecisiones, errores u omisiones\ncontenidos en dicha '
'base de datos, así como daños directos, indirectos o riesgos '
'financieros\nasociados al uso de esta.'
]
for r, row in enumerate(disclaimer):
fig.text(
x=0.05,
y=-0.18 - (r * 0.015),
s=row,
ha='left',
fontdict=dict(size=5, color='gray'),
wrap=True
)
fig.savefig(
fname=output_dir + '/tendencias_{year}{month}{day}.png'.format(
year=year,
month=monthn,
day=dayn
),
dpi=400,
bbox_inches="tight"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment