jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_number_of_proteins(count, accu, colors, outpath, time_name):
    """
    Plot number of quantified proteins and cumulative protein numbers.

    Args:
        count (pd.DataFrame): DataFrame containing count data.
        accu (pd.DataFrame): DataFrame containing accumulation data.
        colors (dict): Dictionary of colors for each cohort.
        outpath (str): Output path for saving the plot.
        time_name (str): Time identifier for the output file.
    """
    fig, ax1 = plt.subplots(figsize=(14, 9))
    sns.barplot(x='Exp', y='count', data=count, hue='cohort', palette=colors, ax=ax1)
    ax1.set_xlabel('Cohort', fontsize=14)
    ax1.set_ylabel('Quantified protein numbers', fontsize=14)
    ax1.legend(loc='upper left', fontsize=10, shadow=True, fancybox=True)
    plt.ylim(0, count['count'].max() * 1.1)

    ax2 = ax1.twinx()
    # sns.lineplot(x='Exp', y='accumulation', data=accu, palette=colors, marker='o', linewidth=2, ax=ax2, label='Your Label')
    sns.lineplot(x='Exp', y='accumulation', data=accu, palette=colors, marker='o', linewidth=2, ax=ax2)
    ax2.set_ylabel('Cumulative protein numbers', fontsize=14)
    ax2.legend().remove()

    plt.title('Quantified protein numbers', fontsize=14)
    plt.savefig(f'{outpath}/GPs_numbers_{time_name}.pdf', dpi=400, transparent=True)
    plt.show()
//  [python]
rows = int(np.ceil(num_plots / cols))

# seaborn plot
fig, axes = plt.subplots(rows, cols, figsize=(cols * 7, rows * 4))
axes = (
    axes.flatten() if isinstance(axes, np.ndarray) else [axes]
)  # make it as a flat list

ax_id = 0
for key in perf_tags:

    sns.tsplot(
        ax=axes[ax_id],
        data=plot_df,
        time=x_tag,
        value=key,
        condition=merged_tag,
        # hue_order=topk_tags_dict[key], # sorted order
        # style=merged_tag,
        # style_order=topk_tags_dict[key],
        # ci=None, # save a lot time without error bars
        interpolate=False,
    )
    axes[ax_id].legend(framealpha=0.5)
    if FLAGS.max_x is not None:
        axes[ax_id].set_xlim(0, FLAGS.max_x)
    ax_id += 1
//  [python]
rows = int(np.ceil(num_plots / cols))

# seaborn plot
fig, axes = plt.subplots(rows, cols, figsize=(cols * 7, rows * 4))
axes = (
    axes.flatten() if isinstance(axes, np.ndarray) else [axes]
)  # make it as a flat list

ax_id = 0
for key in perf_tags:

    sns.lineplot(
        ax=axes[ax_id],
        data=plot_df,
        x=x_tag,
        y=key,
        palette=("blue", "red"),
        hue=merged_tag,
        # hue_order=topk_tags_dict[key], # sorted order
        # style=merged_tag,
        # style_order=topk_tags_dict[key],
        # ci=None, # save a lot time without error bars
        sort=False,
    )
    axes[ax_id].legend(framealpha=0.5)
    if FLAGS.max_x is not None:
        axes[ax_id].set_xlim(0, FLAGS.max_x)
    ax_id += 1
//  [python]
fig, axes = plt.subplots(1, 2, figsize=(6, 1.3), dpi=300, sharey=False)
sns.pointplot(data=dfa, x="L", hue="H", y="MAR", palette=['#a1dab4','#41b6c4','#2c7fb8','#253494'], ax=axes[0], join=True)
//  [python]
fig, axes = plt.subplots(1, 2, figsize=(6, 1.3), dpi=300, sharey=False)
sns.lineplot(data=dfa, x="L", hue="H", y="MAR", palette=['#a1dab4','#41b6c4','#2c7fb8','#253494'], ax=axes[0], marker=".")
//  [python]
def plot_performance(ax, game, agents):
  for agent in agents:
    df_pred = []
    df_time = []
    df_score = []
    log_path = BASE_PATH + '/{}/{}'.format(agent, game)
    SEEDS = os.listdir(log_path)
    for seed in SEEDS:
      df_pred.extend([agent]*MAX_EPOCH)
      df_time.extend(list(range(MAX_EPOCH)))
      seed_log_path = log_path + '/{}/logs'.format(seed)
      iteration_number = plot_utils.get_latest_iteration(seed_log_path)  
      seed_log_path = seed_log_path + '/log_' + str(iteration_number)
      df_score.extend(read_data(seed_log_path, iteration_number))
    df = pd.DataFrame(list(zip(df_pred, df_time, df_score)), 
                      columns=['predicate', 'Steps', 'Score'])
    seaborn.tsplot(data=df, time='Steps', value='Score', unit='predicate', condition='predicate', err_style="sd",  label=agent.upper(),
                     linewidth=1., color=COLORS[agent], ax=ax, legend=False)
    ax.lines[0].set_linestyle('--')
    ax.set_xlim(0,MAX_EPOCH)
//  [python]
def plot_performance(ax, game, agents):
  for agent in agents:
    df_pred = []
    df_time = []
    df_score = []
    log_path = BASE_PATH + '/{}/{}'.format(agent, game)
    SEEDS = os.listdir(log_path)
    for seed in SEEDS:
      df_pred.extend([agent]*MAX_EPOCH)
      df_time.extend(list(range(MAX_EPOCH)))
      seed_log_path = log_path + '/{}/logs'.format(seed)
      iteration_number = plot_utils.get_latest_iteration(seed_log_path)  
      seed_log_path = seed_log_path + '/log_' + str(iteration_number)
      df_score.extend(read_data(seed_log_path, iteration_number))
    df = pd.DataFrame(list(zip(df_pred, df_time, df_score)), 
                      columns=['predicate', 'Steps', 'Score'])
    seaborn.lineplot(x='Steps', y='Score', data=df, ci='sd', label=agent.upper(),
                     linewidth=1., color=COLORS[agent], ax=ax, legend=False)
    ax.lines[0].set_linestyle('--')
    ax.set_xlim(0,MAX_EPOCH)
//  [python]
def replot(self, event=None):
        """Update the plot"""

        df = self.table.getSelectedDataFrame()
        pf = self.table.pf
        if len(df) == 0:
            pf.showWarning('no data selected')
            return
        kwds = dialogs.getWidgetValues(self.widgets)
        pf._initFigure()
        width,height = 8,6
        #print (kwds)
        kind = kwds['kind']
        keep = ['hue','col','row','x','y','palette','kind','col_wrap']
        kwargs = {i:kwds[i] for i in keep}
        for col in ['hue','col','row','x','y','col_wrap']:
            if kwargs[col] in ['',0]:
                del kwargs[col]
        #print (kwargs)
        aspect = height/width        
        sns.set(font_scale=kwds['fontscale'])
        try:
            if kind == 'line':
                del kwargs['kind']
                sns.pointplot(data=df, ax=pf.ax, **kwargs)
                pf.canvas.draw()
                return
            else:
                g = sns.catplot(data=df, height=height, aspect=aspect, **kwargs)
        except Exception as e:
            pf.showWarning(e)
            return
        self.g = g

        pf.setFigure(g.fig)
        pf.canvasResize()
        return
//  [python]
def replot(self, event=None):
        """Update the plot"""

        df = self.table.getSelectedDataFrame()
        pf = self.table.pf
        if len(df) == 0:
            pf.showWarning('no data selected')
            return
        kwds = dialogs.getWidgetValues(self.widgets)
        pf._initFigure()
        width,height = 8,6
        #print (kwds)
        kind = kwds['kind']
        keep = ['hue','col','row','x','y','palette','kind','col_wrap']
        kwargs = {i:kwds[i] for i in keep}
        for col in ['hue','col','row','x','y','col_wrap']:
            if kwargs[col] in ['',0]:
                del kwargs[col]
        #print (kwargs)
        aspect = height/width        
        sns.set(font_scale=kwds['fontscale'])
        try:
            if kind == 'line':
                del kwargs['kind']
                sns.lineplot(data=df, ax=pf.ax, **kwargs)
                pf.canvas.draw()
                return
            else:
                g = sns.catplot(data=df, height=height, aspect=aspect, **kwargs)
        except Exception as e:
            pf.showWarning(e)
            return
        self.g = g

        pf.setFigure(g.fig)
        pf.canvasResize()
        return
//  [python]
def introduction():

    tips = sns.load_dataset("tips")
    fmri = sns.load_dataset("fmri").query("region == 'parietal'")
    penguins = sns.load_dataset("penguins")

    f = mpl.figure.Figure(figsize=(5, 5))
    with sns.axes_style("whitegrid"):
        f.subplots(2, 2)

    sns.scatterplot(
        tips, x="total_bill", y="tip", hue="sex", size="size",
        alpha=.75, palette=["C0", ".5"], legend=False, ax=f.axes[0],
    )
    sns.kdeplot(
        tips.query("size != 5"), x="total_bill", hue="size",
        palette="blend:C0,.5", fill=True, linewidth=.5,
        legend=False, common_norm=False, ax=f.axes[1],
    )
    sns.pointplot(
        fmri, x="timepoint", y="signal", hue="event",
        errorbar=("se", 2), legend=False, palette=["C0", ".5"], ax=f.axes[2],
    )
    sns.boxplot(
        penguins, x="bill_depth_mm", y="species", hue="sex",
        whiskerprops=dict(linewidth=1.5), medianprops=dict(linewidth=1.5),
        boxprops=dict(linewidth=1.5), capprops=dict(linewidth=0),
        width=.5, palette=["C0", ".8"], whis=5, ax=f.axes[3],
    )
    f.axes[3].legend_ = None
    for ax in f.axes:
        ax.set(xticks=[], yticks=[])
    return f
//  [python]
def introduction():

    tips = sns.load_dataset("tips")
    fmri = sns.load_dataset("fmri").query("region == 'parietal'")
    penguins = sns.load_dataset("penguins")

    f = mpl.figure.Figure(figsize=(5, 5))
    with sns.axes_style("whitegrid"):
        f.subplots(2, 2)

    sns.scatterplot(
        tips, x="total_bill", y="tip", hue="sex", size="size",
        alpha=.75, palette=["C0", ".5"], legend=False, ax=f.axes[0],
    )
    sns.kdeplot(
        tips.query("size != 5"), x="total_bill", hue="size",
        palette="blend:C0,.5", fill=True, linewidth=.5,
        legend=False, common_norm=False, ax=f.axes[1],
    )
    sns.lineplot(
        fmri, x="timepoint", y="signal", hue="event",
        errorbar=("se", 2), legend=False, palette=["C0", ".5"], ax=f.axes[2],
    )
    sns.boxplot(
        penguins, x="bill_depth_mm", y="species", hue="sex",
        whiskerprops=dict(linewidth=1.5), medianprops=dict(linewidth=1.5),
        boxprops=dict(linewidth=1.5), capprops=dict(linewidth=0),
        width=.5, palette=["C0", ".8"], whis=5, ax=f.axes[3],
    )
    f.axes[3].legend_ = None
    for ax in f.axes:
        ax.set(xticks=[], yticks=[])
    return f
//  [python]
def plot_data(data, smooth_weight, foi, ax=None):
    interested_columns = [c for c in data.columns if c[-len(foi):] == foi]
    for c in interested_columns:
        x = list(data['global_step'][data[c].notnull()])
        y = data[c][data[c].notnull()]
        y = smooth(list(y), args.smooth_weight)
        plt.plot(x, y, ax=ax)
//  [python]
def plot_data(data, smooth_weight, foi, ax=None):
    interested_columns = [c for c in data.columns if c[-len(foi):] == foi]
    for c in interested_columns:
        x = list(data['global_step'][data[c].notnull()])
        y = data[c][data[c].notnull()]
        y = smooth(list(y), args.smooth_weight)
        sns.lineplot(x=x, y=y, ax=ax)
//  [python]
def plot_all(directory, filename, data_range):
    print("Reading data from {}".format(directory))
    df = pd.read_csv(directory / filename)
    if data_range:
        start, end = data_range.split(':')
        df = df[df["time"].between(int(start), int(end))]
    print("Number of seeds found: {}".format(df.seed.nunique()))
    try:
        custom_processing_return(df)
    except Exception:
        pass
    try:
        df["regret"] = (df["value"] - df["return"]).clip(lower=0)
        df[r"samples $N$"] = 5*df["time"]
        custom_processing_regret(df)
    except Exception:
        pass
    df = df.replace({
        "robust-epc": r"\texttt{Robust}",
        "nominal-epc": r"\texttt{Nominal}",
    })
    df = df.sort_values(by='agent')

    fig, ax = plt.subplots()
    ax.set_yscale("symlog", linthreshy=1e-4)
    sns.pointplot(x=r"samples $N$", y='regret', hue='agent', ax=ax, data=df)
    ax.set_ylabel("suboptimality")
    field = "regret"
    field_path = directory / "{}.pdf".format(field)
    fig.savefig(field_path, bbox_inches='tight')
    field_path = directory / "{}.png".format(field)
    fig.savefig(field_path, bbox_inches='tight')
    print("Saving {} plot to {}".format(field, field_path))

    df = df.groupby(["agent", "time"], as_index=False).max()
    df = df.rename(columns={"regret": "max regret"})

    palette = itertools.cycle(sns.color_palette())
    for agent in df["agent"].unique():
        color = next(palette)
        agent_df = df[df["agent"] == agent]
        ax.plot(agent_df["samples $N$"], agent_df["max regret"], color=color, linestyle="--")

    field = "max_regret"
    field_path = directory / "{}.pdf".format(field)
    fig.savefig(field_path, bbox_inches='tight')
    field_path = directory / "{}.png".format(field)
    fig.savefig(field_path, bbox_inches='tight')
    print("Saving {} plot to {}".format(field, field_path))
//  [python]
def plot_all(directory, filename, data_range):
    print("Reading data from {}".format(directory))
    df = pd.read_csv(directory / filename)
    if data_range:
        start, end = data_range.split(':')
        df = df[df["time"].between(int(start), int(end))]
    print("Number of seeds found: {}".format(df.seed.nunique()))
    try:
        custom_processing_return(df)
    except Exception:
        pass
    try:
        df["regret"] = (df["value"] - df["return"]).clip(lower=0)
        df[r"samples $N$"] = 5*df["time"]
        custom_processing_regret(df)
    except Exception:
        pass
    df = df.replace({
        "robust-epc": r"\texttt{Robust}",
        "nominal-epc": r"\texttt{Nominal}",
    })
    df = df.sort_values(by='agent')

    fig, ax = plt.subplots()
    ax.set_yscale("symlog", linthreshy=1e-4)
    sns.lineplot(x=r"samples $N$", y='regret', hue='agent', ax=ax, data=df)
    ax.set_ylabel("suboptimality")
    field = "regret"
    field_path = directory / "{}.pdf".format(field)
    fig.savefig(field_path, bbox_inches='tight')
    field_path = directory / "{}.png".format(field)
    fig.savefig(field_path, bbox_inches='tight')
    print("Saving {} plot to {}".format(field, field_path))

    df = df.groupby(["agent", "time"], as_index=False).max()
    df = df.rename(columns={"regret": "max regret"})

    palette = itertools.cycle(sns.color_palette())
    for agent in df["agent"].unique():
        color = next(palette)
        agent_df = df[df["agent"] == agent]
        ax.plot(agent_df["samples $N$"], agent_df["max regret"], color=color, linestyle="--")

    field = "max_regret"
    field_path = directory / "{}.pdf".format(field)
    fig.savefig(field_path, bbox_inches='tight')
    field_path = directory / "{}.png".format(field)
    fig.savefig(field_path, bbox_inches='tight')
    print("Saving {} plot to {}".format(field, field_path))
//  [python]
def make_lineplots(df, axs):
    plot_df = df[["coefficient", "estimator","width", "n"]].groupby(["coefficient", "estimator","n"], group_keys=False).mean()["width"].reset_index()
    lplt = sns.pointplot(data=plot_df[(plot_df["coefficient"] == "age") & (plot_df["estimator"] != "imputed")], x="n", y="width", hue="estimator", ax=axs[0], hue_order=["prediction-powered", "classical"], join=True)
    axs[0].set_ylabel("width ($/yr)")
    axs[0].set_xlabel("n")
    axs[0].xaxis.set_tick_params()
    axs[0].yaxis.set_tick_params()
    sns.despine(ax=axs[0],top=True,right=True)
    lplt.get_legend().remove()
    lplt = sns.pointplot(data=plot_df[(plot_df["coefficient"] == "sex") & (plot_df["estimator"] != "imputed")], x="n", y="width", hue="estimator", ax=axs[1], hue_order=["prediction-powered", "classical"], join=True)
    axs[1].set_ylabel("width ($)")
    axs[1].set_xlabel("n")
    axs[1].xaxis.set_tick_params()
    axs[1].yaxis.set_tick_params()
    sns.despine(ax=axs[1],top=True,right=True)
    lplt.get_legend().remove()
//  [python]
def make_lineplots(df, axs):
    plot_df = df[["coefficient", "estimator","width", "n"]].groupby(["coefficient", "estimator","n"], group_keys=False).mean()["width"].reset_index()
    lplt = sns.lineplot(data=plot_df[(plot_df["coefficient"] == "age") & (plot_df["estimator"] != "imputed")], x="n", y="width", hue="estimator", ax=axs[0], hue_order=["prediction-powered", "classical"])
    axs[0].set_ylabel("width ($/yr)")
    axs[0].set_xlabel("n")
    axs[0].xaxis.set_tick_params()
    axs[0].yaxis.set_tick_params()
    sns.despine(ax=axs[0],top=True,right=True)
    lplt.get_legend().remove()
    lplt = sns.lineplot(data=plot_df[(plot_df["coefficient"] == "sex") & (plot_df["estimator"] != "imputed")], x="n", y="width", hue="estimator", ax=axs[1], hue_order=["prediction-powered", "classical"])
    axs[1].set_ylabel("width ($)")
    axs[1].set_xlabel("n")
    axs[1].xaxis.set_tick_params()
    axs[1].yaxis.set_tick_params()
    sns.despine(ax=axs[1],top=True,right=True)
    lplt.get_legend().remove()
//  [python]
def plot(self, ax=None):
        self._validate_plot_params()
        # Use seaborn lineplot with hue='Train' to plot the train and test data
        data = pd.DataFrame(self.explained_covariance_train, columns=["value"])
        data["Mode"] = "Train"  # Add a column indicating train data
        data.index.name = "Latent dimension"
        if self.explained_covariance_test is not None:
            data_test = pd.DataFrame(self.explained_covariance_test, columns=["value"])
            data_test["Mode"] = "Test"  # Add a column indicating test data
            data_test.index.name = "Latent dimension"
            data = pd.concat([data, data_test])  # Concatenate the two dataframes
        if ax is None:
            fig, ax = plt.subplots(figsize=(10, 5))
        else:
            fig = ax.get_figure()
        sns.pointplot(
            data=data, x="Latent dimension", y="value", hue="Mode", ax=ax
        )
        ax.set_xlabel("Latent dimension")
        if self.ratio:
            ax.set_ylabel("Explained covariance %")
            ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
        else:
            ax.set_ylabel("Explained covariance")
        ax.set_title("Explained covariance")
        # Set x-ticks to integers
        ax.xaxis.set_major_locator(plt.MaxNLocator(integer=True))
        plt.tight_layout()
        self.figure_ = fig
        return self
//  [python]
def plot(self, ax=None):
        self._validate_plot_params()
        # Use seaborn lineplot with hue='Train' to plot the train and test data
        data = pd.DataFrame(self.explained_covariance_train, columns=["value"])
        data["Mode"] = "Train"  # Add a column indicating train data
        data.index.name = "Latent dimension"
        if self.explained_covariance_test is not None:
            data_test = pd.DataFrame(self.explained_covariance_test, columns=["value"])
            data_test["Mode"] = "Test"  # Add a column indicating test data
            data_test.index.name = "Latent dimension"
            data = pd.concat([data, data_test])  # Concatenate the two dataframes
        if ax is None:
            fig, ax = plt.subplots(figsize=(10, 5))
        else:
            fig = ax.get_figure()
        sns.lineplot(
            data=data, x="Latent dimension", y="value", style="Mode", marker="o", ax=ax
        )
        ax.set_xlabel("Latent dimension")
        if self.ratio:
            ax.set_ylabel("Explained covariance %")
            ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
        else:
            ax.set_ylabel("Explained covariance")
        ax.set_title("Explained covariance")
        # Set x-ticks to integers
        ax.xaxis.set_major_locator(plt.MaxNLocator(integer=True))
        plt.tight_layout()
        self.figure_ = fig
        return self
//  [python]
def plot_results(args, algorithms):
    n_seeds = args.times
    dataset_ = args.dataset.split('-')
    sub_dir = dataset_[0] + "/" + dataset_[2] # e.g. Mnist/ratio0.5
    os.system("mkdir -p figs/{}".format(sub_dir))  # e.g. figs/Mnist/ratio0.5
    plt.figure(1, figsize=(5, 5))
    TOP_N = 5
    max_acc = 0
    for i, algorithm in enumerate(algorithms):
        algo_name = get_label_name(algorithm)
        ######### plot test accuracy ############
        metrics = [load_results(args, algorithm, seed) for seed in range(n_seeds)]
        all_curves = np.concatenate([metrics[seed]['glob_acc'] for seed in range(n_seeds)])
        top_accs =  np.concatenate([np.sort(metrics[seed]['glob_acc'])[-TOP_N:] for seed in range(n_seeds)] )
        acc_avg = np.mean(top_accs)
        acc_std = np.std(top_accs)
        info = 'Algorithm: {:<10s}, Accuracy = {:.2f} %, deviation = {:.2f}'.format(algo_name, acc_avg * 100, acc_std * 100)
        print(info)
        length = len(all_curves) // n_seeds
        plt.errorbar(
            x=np.array(list(range(length)) * n_seeds) + 1,
            y=all_curves.astype(float),
            fmt='-',
            color=COLORS[i],
            label=algo_name,
            yerr=np.std(all_curves.reshape(n_seeds,-1), axis=0)
        )

    plt.gcf()
    plt.grid()
    plt.title(dataset_[0] + ' Test Accuracy')
    plt.xlabel('Epoch')
    max_acc = np.max([max_acc, np.max(all_curves) ]) + 4e-2

    if args.min_acc < 0:
        alpha = 0.7
        min_acc = np.max(all_curves) * alpha + np.min(all_curves) * (1-alpha)
    else:
        min_acc = args.min_acc
    plt.ylim(min_acc, max_acc)
    fig_save_path = os.path.join('figs', sub_dir, dataset_[0] + '-' + dataset_[2] + '.png')
    plt.savefig(fig_save_path, bbox_inches='tight', pad_inches=0, format='png', dpi=400)
    print('file saved to {}'.format(fig_save_path))
//  [python]
def plot_results(args, algorithms):
    n_seeds = args.times
    dataset_ = args.dataset.split('-')
    sub_dir = dataset_[0] + "/" + dataset_[2] # e.g. Mnist/ratio0.5
    os.system("mkdir -p figs/{}".format(sub_dir))  # e.g. figs/Mnist/ratio0.5
    plt.figure(1, figsize=(5, 5))
    TOP_N = 5
    max_acc = 0
    for i, algorithm in enumerate(algorithms):
        algo_name = get_label_name(algorithm)
        ######### plot test accuracy ############
        metrics = [load_results(args, algorithm, seed) for seed in range(n_seeds)]
        all_curves = np.concatenate([metrics[seed]['glob_acc'] for seed in range(n_seeds)])
        top_accs =  np.concatenate([np.sort(metrics[seed]['glob_acc'])[-TOP_N:] for seed in range(n_seeds)] )
        acc_avg = np.mean(top_accs)
        acc_std = np.std(top_accs)
        info = 'Algorithm: {:<10s}, Accuracy = {:.2f} %, deviation = {:.2f}'.format(algo_name, acc_avg * 100, acc_std * 100)
        print(info)
        length = len(all_curves) // n_seeds
        sns.lineplot(
            x=np.array(list(range(length)) * n_seeds) + 1,
            y=all_curves.astype(float),
            legend='brief',
            color=COLORS[i],
            label=algo_name,
            ci="sd",
        )

    plt.gcf()
    plt.grid()
    plt.title(dataset_[0] + ' Test Accuracy')
    plt.xlabel('Epoch')
    max_acc = np.max([max_acc, np.max(all_curves) ]) + 4e-2

    if args.min_acc < 0:
        alpha = 0.7
        min_acc = np.max(all_curves) * alpha + np.min(all_curves) * (1-alpha)
    else:
        min_acc = args.min_acc
    plt.ylim(min_acc, max_acc)
    fig_save_path = os.path.join('figs', sub_dir, dataset_[0] + '-' + dataset_[2] + '.png')
    plt.savefig(fig_save_path, bbox_inches='tight', pad_inches=0, format='png', dpi=400)
    print('file saved to {}'.format(fig_save_path))
//  [python]
def lineplot(data: DataFrame, x: str, y: str, hue: str, title: str) -> None:
    plt.clf()
    sns.pointplot(data, x=x, y=y, hue=hue).set_title(title)
    fname = re.sub(r"[^\w_. -]", "_", title)
    plt.savefig(f"{fname}.png")
//  [python]
def lineplot(data: DataFrame, x: str, y: str, hue: str, title: str) -> None:
    plt.clf()
    sns.lineplot(data, x=x, y=y, hue=hue).set_title(title)
    fname = re.sub(r"[^\w_. -]", "_", title)
    plt.savefig(f"{fname}.png")
//  [python]
def plot_one_case(
    ax,
    label,
    line_style,
    color_style,
    mark_style,
    line_width=2.0,
    mark_every=5000,
    x=None,
    y=None,
    sns_plot=None,
    remove_duplicate=False,
):
    if sns_plot is not None and not remove_duplicate:
        ax = s.tsplot(
            data=sns_plot["y"],
            label=label,
            linewidth=line_width,
            linestyle=line_style,
            color=color_style,
            marker=mark_style,
            markevery=mark_every,
            markersize=16,
            ax=ax,
        )
    elif sns_plot is not None and remove_duplicate:
        ax = s.tsplot(
            data=sns_plot["y"],
            label=label,
            linewidth=line_width,
            linestyle=line_style,
            color=color_style,
            marker=mark_style,
            markevery=mark_every,
            markersize=16,
            ax=ax,
            estimator=None,
        )
    else:
        ax.plot(
            x,
            y,
            label=label,
            linewidth=line_width,
            linestyle=line_style,
            color=color_style,
            marker=mark_style,
            markevery=mark_every,
            markersize=16,
        )
    return ax
//  [python]
def plot_one_case(
    ax,
    label,
    line_style,
    color_style,
    mark_style,
    line_width=2.0,
    mark_every=5000,
    x=None,
    y=None,
    sns_plot=None,
    remove_duplicate=False,
):
    if sns_plot is not None and not remove_duplicate:
        ax = sns.lineplot(
            x="x",
            y="y",
            data=sns_plot,
            label=label,
            linewidth=line_width,
            linestyle=line_style,
            color=color_style,
            marker=mark_style,
            markevery=mark_every,
            markersize=16,
            ax=ax,
        )
    elif sns_plot is not None and remove_duplicate:
        ax = sns.lineplot(
            x="x",
            y="y",
            data=sns_plot,
            label=label,
            linewidth=line_width,
            linestyle=line_style,
            color=color_style,
            marker=mark_style,
            markevery=mark_every,
            markersize=16,
            ax=ax,
            estimator=None,
        )
    else:
        ax.plot(
            x,
            y,
            label=label,
            linewidth=line_width,
            linestyle=line_style,
            color=color_style,
            marker=mark_style,
            markevery=mark_every,
            markersize=16,
        )
    return ax
//  [python]
def learning_curve(episode_rewards, log_dir, window=10):
    # Calculate rolling window metrics
    rolling_average = episode_rewards.rolling(window=window, min_periods=window).mean().dropna()
    rolling_max = episode_rewards.rolling(window=window, min_periods=window).max().dropna()
    rolling_min = episode_rewards.rolling(window=window, min_periods=window).min().dropna()

    # Change column name
    rolling_average.columns = ['Average Reward']
    rolling_max.columns = ['Max Reward']
    rolling_min.columns = ['Min Reward']
    rolling_data = pd.concat([rolling_average, rolling_max, rolling_min], axis=1)

    # Plot
    sns.set()
    ax = sns.tsplot(data=rolling_data)
    ax.fill_between(rolling_average.index, rolling_min.iloc[:, 0], rolling_max.iloc[:, 0], alpha=0.2)
    ax.set_title('Learning Curve')
    ax.set_ylabel('Reward')
    ax.set_xlabel('Episodes')
    ax.set(ylim=(-100, 100))

    # Save figure
    plt.savefig(log_dir + 'learning_curve' + str(window) + '.png')
//  [python]
def learning_curve(episode_rewards, log_dir, window=10):
    # Calculate rolling window metrics
    rolling_average = episode_rewards.rolling(window=window, min_periods=window).mean().dropna()
    rolling_max = episode_rewards.rolling(window=window, min_periods=window).max().dropna()
    rolling_min = episode_rewards.rolling(window=window, min_periods=window).min().dropna()

    # Change column name
    rolling_average.columns = ['Average Reward']
    rolling_max.columns = ['Max Reward']
    rolling_min.columns = ['Min Reward']
    rolling_data = pd.concat([rolling_average, rolling_max, rolling_min], axis=1)

    # Plot
    sns.set()
    ax = sns.lineplot(data=rolling_data)
    ax.fill_between(rolling_average.index, rolling_min.iloc[:, 0], rolling_max.iloc[:, 0], alpha=0.2)
    ax.set_title('Learning Curve')
    ax.set_ylabel('Reward')
    ax.set_xlabel('Episodes')
    ax.set(ylim=(-100, 100))

    # Save figure
    plt.savefig(log_dir + 'learning_curve' + str(window) + '.png')
//  [python]
def plot_learning_curves(data, plot_var_list, category, save=True):
    """Plot n_errors vs. time, with hue according to the specified category"""

    if data.empty:
        return

    plt.rcParams.update({'font.size': cfg.FONTSIZE})
    _, ax = plt.subplots(figsize=cfg.FIGSIZE)

    lines = []
    names = []
    for plot_vars in plot_var_list:
        label = plot_vars._asdict()[category]
        value = label.lower()
        # if label == 'Primitive':
        #     label = 'Base Actions'
        # else:
        #     label = '+ ' + label + ' Macros'
        if len(data.query(category+'==@value')) > 0:
            sns.tsplot(data=data.query(category+'==@value'),
                         time='transitions', value='n_errors',
                         unit='seed',
                         ax=ax, linewidth=1, alpha=1,
                         color=plot_vars.color, zorder=plot_vars.zorder)
            lines.append(ax.get_lines()[-1])
            names.append(label)

    for _, spine in ax.spines.items():  #ax.spines is a dictionary
        spine.set_zorder(100)
    leg = ax.legend(lines, names, framealpha=1, borderpad=0.5)
    leg.set_draggable(True)
    ax.set_ylim(cfg.YLIM)
    ax.set_xlim(cfg.XLIM)
    ax.xaxis.set_major_locator(ticker.MultipleLocator(plot_vars.tick_size))
    ax.set_xlabel('Generated states' + autoscale_xticks(ax, dtype=float))
    ax.set_ylabel('Remaining errors')
    ax.set_axisbelow(False)
    plt.tight_layout()
    plt.subplots_adjust(top = .96, bottom = .19, right = .95, left = 0.14,
            hspace = 0, wspace = 0)

    # [i.set_linewidth(1) for i in ax.spines.values()]
    if cfg.HLINE:
        ax.hlines(cfg.HLINE, 0, cfg.TRANSITION_CAP, linestyles='dashed', linewidths=1, colors='k')
    if save:
        plt.savefig('results/plots/{}/{}_planning_curves_by_{}.png'.format(
            cfg.DIR, cfg.NAME, category), dpi=100)
    plt.show()
//  [python]
def plot_learning_curves(data, plot_var_list, category, save=True):
    """Plot n_errors vs. time, with hue according to the specified category"""

    if data.empty:
        return

    plt.rcParams.update({'font.size': cfg.FONTSIZE})
    _, ax = plt.subplots(figsize=cfg.FIGSIZE)

    lines = []
    names = []
    for plot_vars in plot_var_list:
        label = plot_vars._asdict()[category]
        value = label.lower()
        # if label == 'Primitive':
        #     label = 'Base Actions'
        # else:
        #     label = '+ ' + label + ' Macros'
        if len(data.query(category+'==@value')) > 0:
            sns.lineplot(data=data.query(category+'==@value'),
                         x='transitions', y='n_errors',
                         legend=False, estimator=None, units='seed',
                         ax=ax, linewidth=1, alpha=1,
                         color=plot_vars.color, zorder=plot_vars.zorder)
            lines.append(ax.get_lines()[-1])
            names.append(label)

    for _, spine in ax.spines.items():  #ax.spines is a dictionary
        spine.set_zorder(100)
    leg = ax.legend(lines, names, framealpha=1, borderpad=0.5)
    leg.set_draggable(True)
    ax.set_ylim(cfg.YLIM)
    ax.set_xlim(cfg.XLIM)
    ax.xaxis.set_major_locator(ticker.MultipleLocator(plot_vars.tick_size))
    ax.set_xlabel('Generated states' + autoscale_xticks(ax, dtype=float))
    ax.set_ylabel('Remaining errors')
    ax.set_axisbelow(False)
    plt.tight_layout()
    plt.subplots_adjust(top = .96, bottom = .19, right = .95, left = 0.14,
            hspace = 0, wspace = 0)

    # [i.set_linewidth(1) for i in ax.spines.values()]
    if cfg.HLINE:
        ax.hlines(cfg.HLINE, 0, cfg.TRANSITION_CAP, linestyles='dashed', linewidths=1, colors='k')
    if save:
        plt.savefig('results/plots/{}/{}_planning_curves_by_{}.png'.format(
            cfg.DIR, cfg.NAME, category), dpi=100)
    plt.show()
//  [python]
aal = pd.read_csv("~/Projects/wqu/MScFE650/GWA1/RawData/AAL.csv", delimiter=',')
aal['Date'] = pd.to_datetime(aal['Date'], format="%d/%m/%Y")
aal['Date_'] = aal['Date']
#  aal.set_index('Date', inplace=True)

#%%
sns.set_style('darkgrid')
sns.plt.plot(aal['Date_'], aal['AdjClose'])
//  [python]
aal = pd.read_csv("~/Projects/wqu/MScFE650/GWA1/RawData/AAL.csv", delimiter=',')
aal['Date'] = pd.to_datetime(aal['Date'], format="%d/%m/%Y")
aal['Date_'] = aal['Date']
#  aal.set_index('Date', inplace=True)

#%%
sns.set_style('darkgrid')
sns.lineplot(x='Date_', y='AdjClose', data=aal)
//  [python]
x1 = x1.T

time = []
for i in range(x1.shape[0]):
    time.append(i)

fig1 = plt.figure()
sns.tsplot(x=time, y=x1)
//  [python]
x1 = x1.T

time = []
for i in range(x1.shape[0]):
    time.append(i)

fig1 = plt.figure()
sns.lineplot(x=time, y=x1)
//  [python]
def plot_coverage(out_dir, coverage_pairs):
    df = pd.DataFrame()

    for label, coverage in coverage_pairs.items():
        df_series = pd.Series(coverage, name="Coverage")
        df_series = df_series.to_frame()
        df[label] = df_series
    axes = sns.tsplot(data=df, ci=None, legend=False)
    axes.set(xlabel="Generated tests", ylabel="Percentage covered")
    fig = axes.get_figure()
    fig.autofmt_xdate()
    plt_name = out_dir.joinpath("plot")
    plt_name = Path(str(plt_name) + "_coverage")
    plt.savefig(plt_name.with_suffix(".pdf"), bbox_inches="tight")
    plt.savefig(plt_name.with_suffix(".png"), bbox_inches="tight")
    plt.gcf().clear()
//  [python]
def plot_coverage(out_dir, coverage_pairs):
    df = pd.DataFrame()

    for label, coverage in coverage_pairs.items():
        df_series = pd.Series(coverage, name="Coverage")
        df_series = df_series.to_frame()
        df[label] = df_series
    axes = sns.lineplot(data=df, ci=None, legend=False)
    axes.set(xlabel="Generated tests", ylabel="Percentage covered")
    fig = axes.get_figure()
    fig.autofmt_xdate()
    plt_name = out_dir.joinpath("plot")
    plt_name = Path(str(plt_name) + "_coverage")
    plt.savefig(plt_name.with_suffix(".pdf"), bbox_inches="tight")
    plt.savefig(plt_name.with_suffix(".png"), bbox_inches="tight")
    plt.gcf().clear()
//  [python]
def get_plot(
    df,
    y_legend,
    yerrs,
    marker_style="o",
    marker_size=50,
    marker_linewidth=2.5,
    capsize=0,
    figsize=(7, 4),
    drop_top_frame=True,
    drop_right_frame=True,
    show_plot=False,
    ax_lim=(0, 1),
    reference_line=None,
    task_name=None,
    work_dir="."
):
    c = cycle(["r", "GoldenRod", "violet", "yellow"])
    c_list = ["r", "GoldenRod"]

    fig, ax = plt.subplots(figsize=figsize)

    ax.set_xlabel("Noise")

    for algo, df_algo in df.groupby("Algorithm"):
        color = next(c)
        plt.plot(df_algo.x, df_algo.y, marker=marker_style, color=color, label=algo)

    i = 0
    for algo, df_algo in df.groupby("Algorithm"):
        color = c_list[1 - i]
        i += 1

        if yerrs[algo] is not None:
            ax.errorbar(x=df_algo.x, y=df_algo.y, yerr=yerrs[algo], fmt="none", color="black", capsize=capsize, zorder=10000)

        if marker_size != 0:
            plt.scatter(
                x=df_algo.x,
                y=df_algo.y,
                marker=marker_style,
                color=color,
                linewidth=marker_linewidth,
                s=marker_size,
                edgecolor="none",
            )

    if drop_top_frame:
        ax.spines["top"].set_visible(False)

    if drop_right_frame:
        ax.spines["right"].set_visible(False)

    ax.set_ylabel(y_legend)
    ax.set_ylim(ax_lim)

    if reference_line is not None:
        ax.axhline(y=reference_line, linestyle="dashed", color="b", label="BS")
    
    if task_name == "Toxicity":
        plt.legend(loc="lower left", frameon=False, fontsize="small")
        plt.xticks(fontsize="x-small")
    else:
        plt.legend([],[], frameon=False)

    folder = f"{work_dir}/images/fig4"
    if not os.path.isdir(folder):
        os.makedirs(folder)
    path = os.path.join(folder, f"{task_name}")
    plt.savefig(f"{path}.pdf", bbox_inches="tight")

    plt.tight_layout(rect=(0, 0, 1, 0.98))
    if show_plot:
        plt.show()

    plt.close()

    return fig, ax
//  [python]
def get_plot(
    df,
    y_legend,
    yerrs,
    marker_style="o",
    marker_size=50,
    marker_linewidth=2.5,
    capsize=0,
    figsize=(7, 4),
    drop_top_frame=True,
    drop_right_frame=True,
    show_plot=False,
    ax_lim=(0, 1),
    reference_line=None,
    task_name=None,
    work_dir="."
):
    c = cycle(["r", "GoldenRod", "violet", "yellow"])
    c_list = ["r", "GoldenRod"]

    fig, ax = plt.subplots(figsize=figsize)

    ax.set_xlabel("Noise")

    sns.lineplot(data=df, x="x", y="y", hue="Algorithm", ax=ax, palette=c)  # , linestyle=linestyle)

    i = 0
    for algo, df_algo in df.groupby("Algorithm"):
        color = c_list[1 - i]
        i += 1

        if yerrs[algo] is not None:
            ax.errorbar(x=df_algo.x, y=df_algo.y, yerr=yerrs[algo], fmt="none", color="black", capsize=capsize, zorder=10000)

        if marker_size != 0:
            sns.scatterplot(
                x=df_algo.x,
                y=df_algo.y,
                marker=marker_style,
                color=color,
                linewidth=marker_linewidth,
                s=marker_size,
                edgecolor="none",
            )

    if drop_top_frame:
        ax.spines["top"].set_visible(False)

    if drop_right_frame:
        ax.spines["right"].set_visible(False)

    ax.set_ylabel(y_legend)
    ax.set_ylim(ax_lim)

    if reference_line is not None:
        ax.axhline(y=reference_line, linestyle="dashed", color="b", label="BS")
    
    if task_name == "Toxicity":
        plt.legend(loc="lower left", frameon=False, fontsize="small")
        plt.xticks(fontsize="x-small")
    else:
        plt.legend([],[], frameon=False)

    folder = f"{work_dir}/images/fig4"
    if not os.path.isdir(folder):
        os.makedirs(folder)
    path = os.path.join(folder, f"{task_name}")
    plt.savefig(f"{path}.pdf", bbox_inches="tight")

    plt.tight_layout(rect=(0, 0, 1, 0.98))
    if show_plot:
        plt.show()

    plt.close()

    return fig, ax
//  [python]
plot_data['y'] = counts
plot_data['style'] = 1

plt.rc('font',family='Times New Roman')
fig, ax = plt.subplots()
sns.pointplot(data=plot_data, x="x", y="y", hue = 'style', join=True, markers=True, legend=False)
//  [python]
plot_data['y'] = counts
plot_data['style'] = 1

plt.rc('font',family='Times New Roman')
fig, ax = plt.subplots()
sns.lineplot(data=plot_data, x="x", y="y", style = 'style', markers=True, legend=False)
//  [python]
def line(data, x, y, hue, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.lineplot.html#seaborn.lineplot

    args = clean_args(locals())

    g = sns.lineplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
    if smooth > 1:
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            datum[value] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)
    sns.set(style="darkgrid", font_scale=1.5)
    sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)
    # sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd', **kwargs)
    """
    If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
    tsplot to lineplot replacing L29 with:

        sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)

    Changes the colorscheme and the default legend style, though.
    """
    plt.legend(loc='best').set_draggable(True)
    #plt.legend(loc='upper center', ncol=3, handlelength=1,
    #           borderaxespad=0., prop={'size': 13})

    """
    For the version of the legend used in the Spinning Up benchmarking page, 
    swap L38 with:

    plt.legend(loc='upper center', ncol=6, handlelength=1,
               mode="expand", borderaxespad=0., prop={'size': 13})
    """

    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        # Just some formatting niceness: x-axis scale in scientific notation if max x is large
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    plt.tight_layout(pad=0.5)
//  [python]
def plot(df, end_time, figname, x="time", y="pct"):
    fig, ax = plt.subplots(figsize=figsize)
    g = s.lineplot(data=df, x=x, y=y, ax=ax)
    plt.axvline(
        end_time,
        figure=fig,
        color="gray",
        linestyle="-",
        label="theoretical",
    )
    plt.fill_between(df[x].values, df[y].values, alpha=0.1)
    plt.xlim((0, 600))
    plt.ylim((0, 100))
    ax.yaxis.set_major_formatter(mpl.ticker.PercentFormatter(decimals=0))
    plt.xlabel("Time (s)")
    plt.ylabel("Reducers completed")
    plt.grid(axis="y")
    filename = figname + ".pdf"
    print(filename)
    plt.savefig(filename, bbox_inches="tight")
//  [python]
def plot(df, end_time, figname, x="time", y="pct"):
    fig, ax = plt.subplots(figsize=figsize)
    g = sns.lineplot(data=df, x=x, y=y, ax=ax)
    plt.axvline(
        end_time,
        figure=fig,
        color="gray",
        linestyle="-",
        label="theoretical",
    )
    plt.fill_between(df[x].values, df[y].values, alpha=0.1)
    plt.xlim((0, 600))
    plt.ylim((0, 100))
    ax.yaxis.set_major_formatter(mpl.ticker.PercentFormatter(decimals=0))
    plt.xlabel("Time (s)")
    plt.ylabel("Reducers completed")
    plt.grid(axis="y")
    filename = figname + ".pdf"
    print(filename)
    plt.savefig(filename, bbox_inches="tight")
//  [python]
def plot_evolution(df, figname, vmax=60.0):
    plt.figure(figsize=(5, 6))
    plt.subplot(1, 1, 1)
    snsplot = sns.tsplot(data=df, time='SSL', value='CLS', unit='corruption', marker="o", palette="husl")
    snsplot.set(xlim=(0.0, vmax), ylim=(0.0, vmax))
    plt.axis('square')
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.savefig(figname, bbox_inches='tight', pad_inches=0)
    print('Save figure to {}'.format(figname))
//  [python]
def plot_evolution(df, figname, vmax=60.0):
    plt.figure(figsize=(5, 6))
    plt.subplot(1, 1, 1)
    snsplot = sns.lineplot(data=df, x='SSL', y='CLS', hue='corruption', marker="o", palette="husl")
    snsplot.set(xlim=(0.0, vmax), ylim=(0.0, vmax))
    plt.axis('square')
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.savefig(figname, bbox_inches='tight', pad_inches=0)
    print('Save figure to {}'.format(figname))
//  [python]
def _plot_pdp(self, test_data, feature_name, path):
        feature_role = self._model.reader._roles[feature_name].name
        # I. Count interpretation
        print("Calculating interpretation for {}:".format(feature_name))
        grid, ys, counts = self._model.get_individual_pdp(
            test_data=test_data,
            feature_name=feature_name,
            n_bins=self.interpretation_params["n_bins"],
            top_n_categories=self.interpretation_params["top_n_categories"],
            datetime_level=self.interpretation_params["datetime_level"],
        )
        # II. Plot pdp
        sns.set(style="whitegrid", font_scale=1.5)
        fig, axs = plt.subplots(2, 1, figsize=(16, 12), gridspec_kw={"height_ratios": [3, 1]})
        axs[0].set_title("PDP plot: " + feature_name)
        n_classes = ys[0].shape[1]
        if n_classes == 1:
            data = pd.concat(
                [pd.DataFrame({"x": grid[i], "y": ys[i].ravel()}) for i, _ in enumerate(grid)]
            ).reset_index(drop=True)
            if feature_role in ["Numeric", "Datetime"]:
                g0 = sns.pointplot(data=data, x="x", y="y", ax=axs[0], color="m")
            else:
                g0 = sns.boxplot(data=data, x="x", y="y", ax=axs[0], showfliers=False, color="m")
        else:
            if self.mapping:
                classes = sorted(self.mapping, key=self.mapping.get)[: self.interpretation_params["top_n_classes"]]
            else:
                classes = np.arange(min(n_classes, self.interpretation_params["top_n_classes"]))
            data = pd.concat(
                [
                    pd.DataFrame({"x": grid[i], "y": ys[i][:, k], "class": name})
                    for i, _ in enumerate(grid)
                    for k, name in enumerate(classes)
                ]
            ).reset_index(drop=True)
            if self._model.reader._roles[feature_name].name in ["Numeric", "Datetime"]:
                g0 = sns.pointplot(data=data, x="x", y="y", hue="class", ax=axs[0])
            else:
                g0 = sns.boxplot(data=data, x="x", y="y", hue="class", ax=axs[0], showfliers=False)
        g0.set(ylabel="y_pred")
        # III. Plot distribution
        counts = np.array(counts) / sum(counts)
        if feature_role == "Numeric":
            g0.set(xlabel="feature value")
            g1 = sns.histplot(test_data[feature_name], kde=True, color="gray", ax=axs[1])
        elif feature_role == "Category":
            g0.set(xlabel=None)
            axs[0].set_xticklabels(grid, rotation=90)
            g1 = sns.barplot(x=grid, y=counts, ax=axs[1], color="gray")
        else:
            g0.set(xlabel=self.interpretation_params["datetime_level"])
            g1 = sns.barplot(x=grid, y=counts, ax=axs[1], color="gray")
        g1.set(xlabel=None)
        g1.set(ylabel="Frequency")
        g1.set(xticklabels=[])
        # IV. Save picture
        plt.tight_layout()
        fig.savefig(path, bbox_inches="tight")
        plt.close()