def daily_timeseries_by_seed(fdir, df_all, channel_list, sweepvar='models', facet_var='ageGroup', agegrp='0-100'):
"""
Parameters:
fdir (str): Directory where the plot will be saved.
df_all (pandas dataframe): Dataframe that includes combined model results.
channel (str): Variable representing the y-axis data to be plotted.
sweepvar (str, optional): Variable to group the data and create multiple lines on the plot. Default is 'models'.
facet_var (str, optional): Variable used to create subplots based on its unique values. Default is 'ageGroup'. (The default should change)
agegrp (str, optional): Age group filter for the data. Default is '5-10'.
Returns:
None (plots are saved to disk).
"""
df_all = df_all[df_all['timestep'] >= 1460] # remove the first 4 years of the 55 year monitoring period
df_all['day_date'] = df_all['timestep'].apply(convert_to_date)
reductions = [f'25%-10%', f'50%-10%', f'50%-25%']
df_all = df_all[df_all['cc_title'].isin(reductions)]
for channel in channel_list:
print(f'#----- Plotting daily timeseries for {channel}-----#')
if channel == 'prevalence_2to10':
ylab = channel.replace('prevalence_2to10', '$\it{Pf}$PR$_{2-10}$ (%)')
else:
ylab = channel.replace('_', ' ')
if facet_var != 'ageGroup' and agegrp is not None:
df = df_all[(df_all.ageGroup == agegrp)]
if agegrp is None:
print('Warning: agegrp is set to None, it will combine all ages, please check your age aggregation')
# df = df_all.groupby(['day_date', sweepvar, facet_var])[channel].agg(np.mean).reset_index()
df = df_all.groupby(['day_date', sweepvar, facet_var, 'seed'])[channel].agg(np.mean).reset_index()
if 'models' not in [sweepvar, facet_var] and len(df['models'].unique()) > 1:
raise ValueError('models needs to be specified in plot if results were combined for more than 1 model')
unique_facets = df[facet_var].unique()
unique_facets = np.sort(unique_facets)
color_palette = sns.color_palette('colorblind', max(len(df['seed'].unique())),4)
nx = 2
ny = 3
f = 1
lower_prevalence = [0.25, 0.5, 0.5]
upper_prevalence = [0.1, 0.1, 0.25]
# Iterate through each facet and plot the lines for each group
for m, model in enumerate(df[sweepvar].unique()):
model_df = df[df[sweepvar] == model]
fig = plt.figure(figsize=(10 * nx, 10 * ny))
f = 1
for i, (facet, facet_df) in enumerate(model_df.groupby([facet_var])):
ax = fig.add_subplot(ny, nx, f)
f = f + 1
for si, (seeds, sdf) in enumerate(facet_df.groupby(['seed'])):
xmean, ymean = get_x_y(sdf, 'day_date', channel, channel)
if model == 'OpenMalaria' and channel == 'eir':
ymean[channel] = ymean[channel] / 5
ymean[f'{channel}_min'] = ymean[f'{channel}_min'] / 5
ymean[f'{channel}_max'] = ymean[f'{channel}_max'] / 5
xmean = xmean['day_date']
merge_df = pd.merge(left=xmean, right=ymean, on='day_date')
merge_df.sort_values(by='day_date', inplace=True)
ax.plot(merge_df['day_date'], merge_df[channel], '-', linewidth=0.5, label=f"{si}",
color=color_palette[m])
x_min_note = merge_df.loc[merge_df['day_date'] == min(merge_df['day_date'])][channel].iloc[0]
x_max_note = merge_df.loc[merge_df['day_date'] == max(merge_df['day_date'])][channel].iloc[0]
year_factor = max(int((max(merge_df['day_date']).year - min(merge_df['day_date']).year) / 8), 1)
ax.annotate(f"{round(x_min_note, 2)}", xy=(min(merge_df['day_date']), x_min_note),
xytext=(min(merge_df['day_date']), x_min_note - int(x_min_note / 10)))
ax.annotate(f"{round(x_max_note, 2)}", xy=(max(merge_df['day_date']), x_max_note), xytext=(
max(merge_df['day_date']) - pd.DateOffset(years=year_factor), x_max_note - int(x_min_note / 15)))
if channel == 'prevalence' or channel == 'prevalence_2to10':
ax.axhline(lower_prevalence[i], linestyle='--')
ax.axhline(upper_prevalence[i], linestyle='--')
ax.set_ylabel(ylab)
ax.set_ylim(-0.1, upper_prevalence[i]+0.1)
ax.xaxis.set_major_locator(mdates.AutoDateLocator(maxticks=8))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax.set_xlabel('Year')
ax.set_title(f'{model}: {facet}')
fname = f'timeseries_daily_{channel}_{agegrp}_by_{model}_by_seed'
fig.savefig(os.path.join(fdir, f'{fname}_zoomedin.png'), bbox_inches='tight')
# fig.savefig(os.path.join(fdir, f'{fname}.pdf'), bbox_inches='tight')
plt.close()