def show_balance_per_day(start, end, df): """ Show the time series of the world: balance per day """ fig, ax = plt.subplots() fig2, ax2 = plt.subplots() start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed', 'recovered', 'deaths'] for variable in variables: dates_, x = get_single_time_series(df, variable, start_index, end_index) data[variable] = cases_per_day(x) data['resolved'] = data['recovered'] + data['deaths'] data['balance'] = data['confirmed'] - data['resolved'] for variable in ['confirmed', 'resolved', 'balance']: ax.plot(dates_[1:], data[variable], 'o-', c=ws.varcolors[variable], label=variable) ax.plot(dates_[1:], data['confirmed'], 'o-', c=ws.varcolors['confirmed'], label='confirmed') ax.plot(dates_[1:], data['resolved'], 'o-', c=ws.varcolors['resolved'], label='resolved') # Date ticks months = mdates.MonthLocator() # every month days = mdates.DayLocator() # every month month_fmt = mdates.DateFormatter('%m') plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) utl.configure_axes(ax, xlims=(dates_[1], dates_[-1]), xlabel='Date', ylabel='New Cases per Day') ax.axhline(y=0, ls='--', c='gray') utl.configure_axes(ax2, xlims=(dates_[1], dates_[-1]), xlabel='Date', ylabel='New Cases per Day') ax2.axhline(y=0, ls='--', c='gray') ax2.set_ylim(0, data['confirmed'].max()) fig.savefig(os.path.join(ws.folders['website/static/images'], 'balance_per_day.png'), bbox_inches='tight') fig2.savefig(os.path.join(ws.folders['website/static/images'], 'balance_per_day_cleaner.png'), bbox_inches='tight')
def show_cases_per_day(start, end, df): """ Show the time series of the growth rate of the virus as new cases per day """ fig, ax = plt.subplots() start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed', 'recovered', 'deaths'] for variable in variables: dates_, x = get_single_time_series(df, variable, start_index, end_index) data[variable] = cases_per_day(x) ax.plot(dates_[1:], data[variable], 'o-', c=ws.varcolors[variable], label=variable) # Second graph: only recovered and deaths, in log scale fig2, ax2 = plt.subplots() ax2.plot(dates_[1:], data['recovered'], 'o-', c=ws.varcolors['recovered'], label='recovered') ax2.plot(dates_[1:], data['deaths'], 'o-', c=ws.varcolors['deaths'], label='deaths') ax2.set_yscale('log') utl.configure_axes(ax2, xlims=(dates_[1], dates_[-1]), xlabel='Date', ylabel='New Cases per Day') # Date ticks months = mdates.MonthLocator() # every month days = mdates.DayLocator() # every month month_fmt = mdates.DateFormatter('%m') plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) utl.configure_axes(ax, xlims=(dates_[1], dates_[-1]), xlabel='Date', ylabel='New Cases per Day') fig.savefig(os.path.join(ws.folders['website/static/images'], 'cases_per_day.png'), bbox_inches='tight')
def show_world_death_ratio_I(start, end, df, country='world'): """ Show the time series of the death ratios """ fig, ax = plt.subplots() start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed', 'recovered', 'deaths'] for variable in variables: dates_, data[variable] = get_single_time_series( df, variable, start_index, end_index) # Variable 'death ratio' data['resolved'] = data['recovered'] + data['deaths'] data['deaths over total'] = data['deaths'] / data['confirmed'] data['deaths over resolved'] = data['deaths'] / data['resolved'] ax.plot(dates_, data['deaths over total'], c=ws.varcolors['deaths'], ls='-', label='deaths over total') ax.plot(dates_, data['deaths over resolved'], c=ws.varcolors['deaths'], ls='--', label='deaths over closed cases') # Date ticks months = mdates.MonthLocator() # every month days = mdates.DayLocator() # every month month_fmt = mdates.DateFormatter('%m') # format the ticks if False: ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(month_fmt) ax.xaxis.set_minor_locator(days) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) utl.configure_axes(ax, xlims=(dates_[0], dates_[-1]), xlabel='Date', ylabel='Ratios') fig.savefig(os.path.join(ws.folders['website/static/images'], 'world_death_ratio_I.png'), bbox_inches='tight')
def show_country(country, variables, start, end, df, fig=None, ax=None): """ Plot the time series of 'variable' from 'start' to 'end', and for 'country' """ if fig is None and ax is None: fig, ax = plt.subplots() start_index, end_index = get_start_end(start, end) # Select the data for 'country' df_ = df[df['Country/Region'] == country] # 'variables' can be either one string or a list if isinstance(variables, list): pass elif isinstance(variables, str): # Turn it into a list variables = [variables] else: print( 'ERROR: argument \'variables\' needs to be a string or list of strings' ) return for variable in variables: data = [] dates_ = [] dates_, data = get_single_time_series(df_, variable, start_index, end_index) # Show time series ax.plot(dates_, data, c=ws.varcolors[variable], label=variable) utl.configure_axes(ax, xlims=(dates_[0], dates_[-1]), xlabel='Date', ylabel='Cases') ax.set_title(country) # ax.set_yscale('log') fig.savefig(os.path.join( ws.folders['website/static/images'], '%s_nolog.png' % country.replace(' ', '_').lower()), bbox_inches='tight')
def show_world_time_series(start, end, df): """ Show the time series of the world """ fig, ax = plt.subplots() start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed', 'recovered', 'deaths'] for variable in variables: dates_, data[variable] = get_single_time_series( df, variable, start_index, end_index) # Existing cases data['resolved'] = data['recovered'] + data['deaths'] data['existing'] = data['confirmed'] - data['resolved'] variables = variables + ['existing'] for variable in variables: ax.plot(dates_, data[variable], c=ws.varcolors[variable], label=variable) # Date ticks months = mdates.MonthLocator() # every month days = mdates.DayLocator() # every month month_fmt = mdates.DateFormatter('%m') # format the ticks if False: ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(month_fmt) ax.xaxis.set_minor_locator(days) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) utl.configure_axes(ax, xlims=(dates_[0], dates_[-1]), xlabel='Date', ylabel='Cases') ax.set_ylim(0, data['confirmed'].max()) fig.savefig(os.path.join(ws.folders['website/static/images'], 'world.png'), bbox_inches='tight')
def countries_dayn(n, countries): """ Show countries from the day they reached or surpassed n cases """ # Get data df = ws.data_countries_only # Parameters linewidths = {k: 1 for k in countries} linewidths['Colombia'] = 2 end = '01/04/2020' # Create figures fig1, ax1 = plt.subplots() fig2, ax2 = plt.subplots() fig3, ax3 = plt.subplots() # Iterate over countries to plot data for country in countries: # Find the day when n cases were reached for each country # First, get the whole time series dates_, x = get_single_time_series(df[df['country_region'] == country], 'confirmed', 0, ws.date_indices['01/04/2020']) # Find where the country reached the n cases date_index = np.where(x >= n)[0][0] start = ws.dates_keys[date_index] start_index, end_index = get_start_end(start, end) data = {} daysmin = 1e99 daysmax = -1e99 dates_, x = get_single_time_series(df[df['country_region'] == country], 'confirmed', start_index, end_index) data['confirmed'] = x[:] # Get new cases in 7 days data_n7d = get_new_7_days(start_index, end_index, 'confirmed', country=country, avg=True) # Days days = np.arange(len(dates_)) daysmin = min(days.min(), daysmin) daysmax = max(days.max(), daysmax) # CASOS CONFIRMADOS ax1.plot(days, data['confirmed'], 'o-', lw=linewidths[country], label=country) # VELOCIDAD c = data['confirmed'] velocidad = c[1:] - c[:-1] velocidad = data_n7d['new_7_days'] # ax2.plot(days[1:], velocidad, 'o-', lw=linewidths[country], label=country) ax2.plot(days, velocidad, 'o-', lw=linewidths[country], label=country) # ACELERACIÓN aceleracion = velocidad[1:] - velocidad[:-1] # ax3.plot(days[2:], aceleracion, 'o-', lw=linewidths[country], label=country) ax3.plot(days[1:], aceleracion, 'o-', lw=linewidths[country], label=country) # Arrange figures # 1 ax1.set_ylim(0, 1100) # ax1.set_yscale('log') utl.configure_axes(ax1, xlims=(daysmin, 14), xlabel='Días después de alcanzar %i casos' % n, ylabel='Casos confirmados') ax1.set_title('Casos confirmados') # 2 # ax2.set_ylim(0, 500) ax2.set_ylim(0, 250) # ax2.set_yscale('log') utl.configure_axes(ax2, xlims=(daysmin, 14), xlabel='Días después de alcanzar %i casos' % n, ylabel='Velocidad (casos confirmados nuevos diarios)') utl.configure_axes( ax2, xlims=(daysmin, 14), xlabel='Días después de alcanzar %i casos' % n, ylabel= 'Velocidad (casos confirmados nuevos diarios;\npromedio de 7 días)') ax2.set_title('Velocidad') # 3 # ax3.set_ylim(-10, 100) ax3.set_ylim(-10, 50) # ax3.set_yscale('log') ax3.axhline(y=0, ls='--', c='grey') utl.configure_axes( ax3, xlims=(daysmin, 14), xlabel='Días después de alcanzar %i casos' % n, ylabel='Aceleración (aumento diario de casos confirmados nuevos)') utl.configure_axes( ax3, xlims=(daysmin, 14), xlabel='Días después de alcanzar %i casos' % n, ylabel= 'Aceleración (aumento diario de casos confirmados nuevos;\npromedio de 7 días)' ) ax3.set_title('Aceleración') # Save figures fig1.savefig(os.path.join( ws.folders['website/static/images'], 'custom_casos_%i_%s_v2.png' % (n, ''.join([c[0] for c in countries]))), bbox_inches='tight', dpi=300) fig2.savefig(os.path.join( ws.folders['website/static/images'], 'custom_velocidad_%i_%s_v4.png' % (n, ''.join([c[0] for c in countries]))), bbox_inches='tight', dpi=300) fig3.savefig(os.path.join( ws.folders['website/static/images'], 'custom_aceleracion_%i_%s_v2.png' % (n, ''.join([c[0] for c in countries]))), bbox_inches='tight', dpi=300)
def analysis_03(start, end, df): """ """ countries = ['Spain', 'Italy', 'Colombia'] countries = ['Spain', 'Italy', 'Colombia', 'Korea, South', 'France'] fig3, ax3 = plt.subplots() colors = { 'Spain': 'k', 'Colombia': 'r', 'Italy': 'b', 'Korea, South': 'g', 'France': 'orange', } linewidths = { 'Spain': 1, 'Colombia': 2, 'Korea, South': 1, 'Italy': 1, 'France': 1, } start_by_country3 = { 'Spain': ws.dates_keys[33], 'Colombia': ws.dates_keys[47], 'Italy': ws.dates_keys[29], 'Korea, South': ws.dates_keys[28], 'France': ws.dates_keys[34], } for country in countries: start = start_by_country3[country] start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed', 'deaths', 'recovered'] daysmin = 1e99 daysmax = -1e99 for variable in variables: dates_, x = get_single_time_series( df[df['Country/Region'] == country], variable, start_index, end_index) data[variable] = x[:] # Existing cases data['resolved'] = data['recovered'] + data['deaths'] data['existing'] = data['confirmed'] - data['resolved'] days = np.arange(len(dates_)) daysmin = min(days.min(), daysmin) daysmax = max(days.max(), daysmax) ax3.plot(days, data['existing'], 'o-', lw=linewidths[country], c=colors[country], alpha=0.5, label=country) utl.configure_axes(ax3, xlims=(daysmin, 15), xlabel='Days after Growth Rate Departure', ylabel='New Cases per Day') ax3.set_ylim(0, 1000) ax3.set_title('Existing Cases') fig3.savefig(os.path.join(ws.folders['website/static/images'], 'activos_05_02.png'), bbox_inches='tight')
def analysis_02(start, end, df): """ """ countries = ['Spain', 'Italy', 'Colombia'] fig, ax = plt.subplots() fig2, ax2 = plt.subplots() colors = {'Spain': 'k', 'Colombia': 'r', 'Italy': 'b'} linewidths = {'Spain': 1, 'Colombia': 2, 'Italy': 1} start_by_country12 = { 'Spain': ws.dates_keys[10], 'Colombia': ws.dates_keys[44], 'Italy': ws.dates_keys[9] } for country in countries: start = start_by_country12[country] start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed', 'deaths', 'recovered'] daysmin = 1e99 daysmax = -1e99 for variable in variables: dates_, x = get_single_time_series( df[df['Country/Region'] == country], variable, start_index, end_index) data[variable] = x[:] # Existing cases data['resolved'] = data['recovered'] + data['deaths'] data['existing'] = data['confirmed'] - data['resolved'] days = np.arange(len(dates_)) daysmin = min(days.min(), daysmin) daysmax = max(days.max(), daysmax) ax.plot(days, data['existing'], 'o-', lw=linewidths[country], c=colors[country], alpha=0.5, label=country) ax2.plot(days, data['existing'], 'o-', lw=linewidths[country], c=colors[country], alpha=0.5, label=country) utl.configure_axes(ax, xlims=(daysmin, 20), xlabel='Days after First Case', ylabel='New Cases per Day') utl.configure_axes(ax2, xlims=(daysmin, 30), xlabel='Days after First Case', ylabel='New Cases per Day') ax.set_ylim(0, 40) ax.set_title('Existing Cases') # fig.savefig(os.path.join(ws.folders['website/static/images'], 'activos_01.png'), bbox_inches='tight') ax2.set_ylim(0, 40) ax2.set_title('Existing Cases')
def analysis_01(start, end, df): """ """ countries = ['Spain', 'Italy', 'Colombia'] fig, ax = plt.subplots() colors = {'Spain': 'k', 'Colombia': 'r', 'Italy': 'b'} linewidths = {'Spain': 1, 'Colombia': 2, 'Italy': 1} start_by_country = { 'Spain': ws.dates_keys[10], 'Colombia': ws.dates_keys[44], 'Italy': ws.dates_keys[9] } for country in countries: start = start_by_country[country] start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed'] daysmin = 1e99 daysmax = -1e99 for variable in variables: dates_, x = get_single_time_series( df[df['Country/Region'] == country], variable, start_index, end_index) data[variable] = cases_per_day(x) days = np.arange(len(dates_) - 1) daysmin = min(days.min(), daysmin) daysmax = max(days.max(), daysmax) ax.plot(days, data[variable], 'o-', lw=linewidths[country], c=colors[country], alpha=0.5, label=country) # Date ticks months = mdates.MonthLocator() # every month days = mdates.DayLocator() # every month month_fmt = mdates.DateFormatter('%m') utl.configure_axes(ax, xlims=(daysmin, 20), xlabel='Days after First Case', ylabel='New Cases per Day') ax.set_ylim(0, 40) ax.set_title('Growth Rate (New Cases per Day)') fig.savefig(os.path.join(ws.folders['website/static/images'], 'ritmos_01.png'), bbox_inches='tight')
def stackplot(start, end, df): """ Row-stack graph of the infection """ # Over confirmed # Absolute fig, ax = plt.subplots() start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed', 'recovered', 'deaths'] for variable in variables: dates_, data[variable] = get_single_time_series( df, variable, start_index, end_index) data['resolved'] = data['recovered'] + data['deaths'] data['existing'] = data['confirmed'] - data['resolved'] wanted_variables = ('deaths', 'recovered', 'existing') values = np.row_stack(np.array([data[k] for k in wanted_variables])) ax.stackplot( dates_, values, colors=[ws.varcolors[k] for k in wanted_variables], labels=wanted_variables, ) ax.plot(dates_, data['confirmed'], c=ws.varcolors['confirmed'], ls='-', label='confirmed') utl.configure_axes(ax, xlims=(dates_[0], dates_[-1]), xlabel='Date', ylabel='Cases', title='Evolution over Confirmed') fig.savefig(os.path.join(ws.folders['website/static/images'], 'stackplot.png'), bbox_inches='tight') # Percentage fig2, ax2 = plt.subplots() start_index, end_index = get_start_end(start, end) data = {} variables = ['confirmed', 'recovered', 'deaths'] for variable in variables: dates_, data[variable] = get_single_time_series( df, variable, start_index, end_index) data['resolved'] = data['recovered'] + data['deaths'] data['existing'] = data['confirmed'] - data['resolved'] values = np.row_stack( np.array([data['deaths'], data['recovered'], data['existing']]) * (100. / data['confirmed'])) ax2.stackplot( dates_, values, colors=[ws.varcolors[k] for k in wanted_variables], labels=wanted_variables, ) ax2.set_ylim(0, 100) utl.configure_axes(ax2, xlims=(dates_[0], dates_[-1]), xlabel='Date', ylabel='Cases (%)', title='Evolution over Confirmed') fig2.savefig(os.path.join(ws.folders['website/static/images'], 'stackplot_percentages.png'), bbox_inches='tight')