jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def line_plot(self):
        display(Markdown('**--------------------box plot of each column segmented by another column--------------------**'))

        for x in self.categorical_variables:
                
                df_d=self.dataframe.groupby([timeseries,x], as_index=False)[value].agg({'group_size':'sum'})
                sns.lineplot(data=df_d, x=timeseries, hue=x,  y="group_size") 
                plt.legend(loc="upper right", bbox_to_anchor=(1.2,1.0))
                plt.ylabel(x)
                plt.xlabel(timeseries)
                plt.title('Time series plot of '+ x + ' and ' + timeseries)
                plt.grid(True)
                plt.show()
//  [python]
def make_zoom_plot(
    plot_df, figure_name=None,
    xlim=None, ylim=None,
    figsize=(7.5, 6), dpi = 150,
    zoom_xlim=None, zoom_ylim=None,
    zoomed_location = [1.05, 0.05, 0.37, 0.9]
    ):
    """Make tradeoff plots with zoomed-in area.

    Args:
        plot_df (pd.DataFrame): a pd.DataFrame including numbers for each method.
        figure_name (str, optional): save the plot with figure_name. Defaults to None.
        xlim (tuple, optional): x-axis limit. Defaults to None.
        ylim (tuple, optional): y-aix limit. Defaults to None.
        figsize (tuple, optional): figure size. Defaults to (7.5, 6).
        dpi (int, optional): figure resolution. Defaults to 150.
        zoom_xlim (tuple, optional): x-axis interval of the zoomed-in area. Defaults to None.
        zoom_ylim (tuple, optional): y-axis interval of the zoomed-in area. Defaults to None.
        zoomed_location (list, optional): location of the zoomed-in area, [x, y, length, height]. Defaults to [1.05, 0.05, 0.37, 0.9].
    """

    plot_df["Fairness"] = plot_df["test_fairness mean"]
    plot_df["Accuracy"] = plot_df["test_performance mean"]

    # fig, ax = plt.subplots(1, 2, figsize=figsize, dpi = dpi, gridspec_kw={'width_ratios': [0.8, 0.2]})
    fig, ax = plt.subplots(figsize=figsize, dpi = dpi)

    with sns.axes_style("white"):
        sns.pointplot(
            data=plot_df,
            x="Accuracy",
            y="Fairness",
            hue="Models",
            markers=True,
            ax=ax
        )
    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)

    sns.move_legend(ax, "lower left")

    axins = ax.inset_axes(zoomed_location)
    with sns.axes_style("white"):
        sns.pointplot(
            data=plot_df,
            x="Accuracy",
            y="Fairness",
            hue="Models",
            markers=True,
            legend=False,
            ax=axins
        )

    axins.xaxis.set_visible(False)
    axins.yaxis.set_visible(False)
    
    axins.set_xlim(zoom_xlim)
    axins.set_ylim(zoom_ylim)
    
    ax.indicate_inset_zoom(axins, edgecolor="black")
    
    if figure_name is not None:
        fig.savefig(figure_name+".pdf", format="pdf", dpi=960, bbox_inches="tight")
//  [python]
def make_zoom_plot(
    plot_df, figure_name=None,
    xlim=None, ylim=None,
    figsize=(7.5, 6), dpi = 150,
    zoom_xlim=None, zoom_ylim=None,
    zoomed_location = [1.05, 0.05, 0.37, 0.9]
    ):
    """Make tradeoff plots with zoomed-in area.

    Args:
        plot_df (pd.DataFrame): a pd.DataFrame including numbers for each method.
        figure_name (str, optional): save the plot with figure_name. Defaults to None.
        xlim (tuple, optional): x-axis limit. Defaults to None.
        ylim (tuple, optional): y-aix limit. Defaults to None.
        figsize (tuple, optional): figure size. Defaults to (7.5, 6).
        dpi (int, optional): figure resolution. Defaults to 150.
        zoom_xlim (tuple, optional): x-axis interval of the zoomed-in area. Defaults to None.
        zoom_ylim (tuple, optional): y-axis interval of the zoomed-in area. Defaults to None.
        zoomed_location (list, optional): location of the zoomed-in area, [x, y, length, height]. Defaults to [1.05, 0.05, 0.37, 0.9].
    """

    plot_df["Fairness"] = plot_df["test_fairness mean"]
    plot_df["Accuracy"] = plot_df["test_performance mean"]

    # fig, ax = plt.subplots(1, 2, figsize=figsize, dpi = dpi, gridspec_kw={'width_ratios': [0.8, 0.2]})
    fig, ax = plt.subplots(figsize=figsize, dpi = dpi)

    with sns.axes_style("white"):
        sns.lineplot(
            data=plot_df,
            x="Accuracy",
            y="Fairness",
            hue="Models",
            markers=True,
            style="Models",
            ax=ax
        )
    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)

    sns.move_legend(ax, "lower left")

    axins = ax.inset_axes(zoomed_location)
    with sns.axes_style("white"):
        sns.lineplot(
            data=plot_df,
            x="Accuracy",
            y="Fairness",
            hue="Models",
            markers=True,
            style="Models",
            legend=False,
            ax=axins
        )

    axins.xaxis.set_visible(False)
    axins.yaxis.set_visible(False)
    
    axins.set_xlim(zoom_xlim)
    axins.set_ylim(zoom_ylim)
    
    ax.indicate_inset_zoom(axins, edgecolor="black")
    
    if figure_name is not None:
        fig.savefig(figure_name+".pdf", format="pdf", dpi=960, bbox_inches="tight")
//  [python]
display_types = ['reward', 'success rate']
display_type = display_types[1]

sns.set(style="darkgrid", font_scale=1.5)


fig1 = plt.figure()
sns.plt.plot(time, x1)
//  [python]
display_types = ['reward', 'success rate']
display_type = display_types[1]

sns.set(style="darkgrid", font_scale=1.5)


fig1 = plt.figure()
sns.lineplot(x=time, y=x1)
//  [python]
def plot_average(input_filename, output_filename, keep_ylabels=False):
    functions = ["swap", "echo", "copy", "repeat", "shift", "reverse", "append", "prepend", "remove_first", "remove_second"]
    # Increase parameters when reading out the files with results per length
    results = numpy.zeros((3, 10, 19))
    run = -1
    function = -1
    with open(input_filename) as f:
        for line in f:
            if "Run" in line:
                run += 1
                function = -1
            if "Function" in line:
                function += 1
            if "Length" in line:
                line = line.split()
                l = line[1]
                seqacc = line[-1]
                # Argument sizes run from 2 to 20
                results[run, function, int(l) - 2] = float(seqacc)

    # Figure size
    if keep_ylabels:
        sns.set(rc={'figure.figsize':(6,3.5), "lines.linewidth": 3})
    else:
        sns.set(rc={'figure.figsize':(4,3.5), "lines.linewidth": 3})
    n_chars = range(2, 21)
    results = results.reshape((1, 30, 19))
    average_all = numpy.mean(results, 1)[0]
    std_all = numpy.std(results, 1)[0]

    # Mean
    ax = sns.tsplot(time=n_chars, data=average_all, color="blue", marker="^")
    # - STD
    ax.fill_between(n_chars, average_all - std_all, average_all, color="blue", alpha=0.2)
    # + STD
    ax.fill_between(n_chars, average_all + std_all, average_all, color="blue", alpha=0.2)
    plt.xticks(list(range(2, 21, 2)))
    plt.ylim(-0.02, 1.02)
    plt.xlim(2, 20)
    ax.grid(False)

    # Share axes for subplots displayed next to each other in the paper
    if keep_ylabels:
        plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
        plt.ylabel("accuracy")
        ax.set_ylabel("accuracy",fontsize=20)
        ax.tick_params(labelsize=20)
    else:
        plt.yticks([])

    ax.set_xlabel("number of characters", fontsize=20)
    ax.tick_params(labelsize=20)
    plt.savefig(output_filename, bbox_inches='tight')
    plt.clf()
//  [python]
def plot_average(input_filename, output_filename, keep_ylabels=False):
    functions = ["swap", "echo", "copy", "repeat", "shift", "reverse", "append", "prepend", "remove_first", "remove_second"]
    # Increase parameters when reading out the files with results per length
    results = numpy.zeros((3, 10, 19))
    run = -1
    function = -1
    with open(input_filename) as f:
        for line in f:
            if "Run" in line:
                run += 1
                function = -1
            if "Function" in line:
                function += 1
            if "Length" in line:
                line = line.split()
                l = line[1]
                seqacc = line[-1]
                # Argument sizes run from 2 to 20
                results[run, function, int(l) - 2] = float(seqacc)

    # Figure size
    if keep_ylabels:
        sns.set(rc={'figure.figsize':(6,3.5), "lines.linewidth": 3})
    else:
        sns.set(rc={'figure.figsize':(4,3.5), "lines.linewidth": 3})
    n_chars = range(2, 21)
    results = results.reshape((1, 30, 19))
    average_all = numpy.mean(results, 1)[0]
    std_all = numpy.std(results, 1)[0]

    # Mean
    ax = sns.lineplot(x=n_chars, y=average_all, color="blue", marker="^")
    # - STD
    ax.fill_between(n_chars, average_all - std_all, average_all, color="blue", alpha=0.2)
    # + STD
    ax.fill_between(n_chars, average_all + std_all, average_all, color="blue", alpha=0.2)
    plt.xticks(list(range(2, 21, 2)))
    plt.ylim(-0.02, 1.02)
    plt.xlim(2, 20)
    ax.grid(False)

    # Share axes for subplots displayed next to each other in the paper
    if keep_ylabels:
        plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
        plt.ylabel("accuracy")
        ax.set_ylabel("accuracy",fontsize=20)
        ax.tick_params(labelsize=20)
    else:
        plt.yticks([])

    ax.set_xlabel("number of characters", fontsize=20)
    ax.tick_params(labelsize=20)
    plt.savefig(output_filename, bbox_inches='tight')
    plt.clf()
//  [python]
df = load.intraday_prices()
df["hour"] = df["product_time"].dt.hour

f, (ax1, ax2) = plt.subplots(1, 2)
f.set_size_inches(18.5, 10.5)

sns.tsplot(x="hour", y="clearing_price_mwh", data=df, ax=ax1)
//  [python]
df = load.intraday_prices()
df["hour"] = df["product_time"].dt.hour

f, (ax1, ax2) = plt.subplots(1, 2)
f.set_size_inches(18.5, 10.5)

sns.lineplot(x="hour", y="clearing_price_mwh", data=df, ax=ax1)
//  [python]
def observe_ts(self):
        plt.plot(self.data['X'], self.data['Y'])
        plt.show()
        plt.close()
//  [python]
def observe_ts(self):
        sns.lineplot(x=self.data['X'], y=self.data['Y'])
        plt.show()
        plt.close()
//  [python]
def plot_train_val_curves(self, save_file=None):
		"""Plots training and validation curves.

		Parameters
		----------
		save_file:str
			File to save to.

		"""
		plt.figure()
		sns.pointplot(x='epoch',y='value',hue='variable',
					 data=pd.DataFrame(np.vstack((np.arange(len(self.train_losses)),self.train_losses,self.val_losses)).T,
									   columns=['epoch','train','val']).melt(id_vars=['epoch'],value_vars=['train','val']))
		if save_file is not None:
			plt.savefig(save_file, dpi=300)
//  [python]
def plot_train_val_curves(self, save_file=None):
		"""Plots training and validation curves.

		Parameters
		----------
		save_file:str
			File to save to.

		"""
		plt.figure()
		sns.lineplot('epoch','value',hue='variable',
					 data=pd.DataFrame(np.vstack((np.arange(len(self.train_losses)),self.train_losses,self.val_losses)).T,
									   columns=['epoch','train','val']).melt(id_vars=['epoch'],value_vars=['train','val']))
		if save_file is not None:
			plt.savefig(save_file, dpi=300)
//  [python]
def plot_with_bands(ts, state, label, ax, idx=1, converter=None):
  mean = kf_states[:, state].flatten()
  stds = np.sqrt(kf_ps[:, state, state].flatten())

  if converter is not None:
    mean = converter(mean)
    stds = converter(stds)

  plt.plot(ts, mean, label=label, ax=ax)
  ax.fill_between(ts, mean - stds, mean + stds, alpha=.2, color=palette[idx])
//  [python]
def plot_with_bands(ts, state, label, ax, idx=1, converter=None):
  mean = kf_states[:, state].flatten()
  stds = np.sqrt(kf_ps[:, state, state].flatten())

  if converter is not None:
    mean = converter(mean)
    stds = converter(stds)

  sns.lineplot(ts, mean, label=label, ax=ax)
  ax.fill_between(ts, mean - stds, mean + stds, alpha=.2, color=palette[idx])
//  [python]
def plot(self, ylim: list[float] | None = None) -> None:
        """ICEを可視化

        Args:
            ylim: Y軸の範囲。特に指定しなければiceの範囲となる。
        """

        fig, ax = plt.subplots()
        # ICEの線
        sns.pointplot(
            self.target_var_name,
            "ice",
            units="instance",
            data=self.df_ice,
            lw=0.8,
            alpha=0.5,
            estimator=None,
            zorder=1,  # zorderを指定することで、線が背面、点が前面にくるようにする
            ax=ax,
        )
        # インスタンスからの実際の予測値を点でプロットしておく
        sns.scatterplot(
            self.target_var_name, 
            "prediction", 
            data=self.df_instance, 
            zorder=2, 
            ax=ax
        )
        ax.set(xlabel=self.target_var_name, ylabel="Prediction", ylim=ylim)
        fig.suptitle(
            f"Individual Conditional Expectation({self.target_var_name})"
        )
        
        fig.show()
//  [python]
def plot(self, ylim: list[float] | None = None) -> None:
        """ICEを可視化

        Args:
            ylim: Y軸の範囲。特に指定しなければiceの範囲となる。
        """

        fig, ax = plt.subplots()
        # ICEの線
        sns.lineplot(
            self.target_var_name,
            "ice",
            units="instance",
            data=self.df_ice,
            lw=0.8,
            alpha=0.5,
            estimator=None,
            zorder=1,  # zorderを指定することで、線が背面、点が前面にくるようにする
            ax=ax,
        )
        # インスタンスからの実際の予測値を点でプロットしておく
        sns.scatterplot(
            self.target_var_name, 
            "prediction", 
            data=self.df_instance, 
            zorder=2, 
            ax=ax
        )
        ax.set(xlabel=self.target_var_name, ylabel="Prediction", ylim=ylim)
        fig.suptitle(
            f"Individual Conditional Expectation({self.target_var_name})"
        )
        
        fig.show()
//  [python]
def main(statsfile, bs):
    df = parse_stats_file(statsfile)
    s.lineplot(x="step", y="t", hue="kind", data=df).set(
        title=f"Time per element by noise quality, batch_size={bs}", ylabel="µs"
    )
    plt.show()
//  [python]
def main(statsfile, bs):
    df = parse_stats_file(statsfile)
    seaborn.lineplot(x="step", y="t", hue="kind", data=df).set(
        title=f"Time per element by noise quality, batch_size={bs}", ylabel="µs"
    )
    plt.show()
//  [python]
def plot_forecast(
    actuals: pd.Series,
    predictions: pd.Series,
    cutoff: str,
    events: List[Dict[str, Any]],
):
    """Plot a forecast that's cutoff before actuals finish"""
    base_prophet_df = base_prophet_forecast(
        actuals=actuals, cutoff=cutoff, events=events
    )
    # Find cutoff date for plot
    plot_cutoff = min(
        [base_prophet_df.ds.max(), actuals.index.max(), predictions.index.max()]
    )
    predict_df = (
        predictions.reset_index()
        .rename(columns={"index": "ds", "forecast": "value"})
        .assign(method="judgyprophet")
        .loc[:, ["ds", "value", "insample", "method"]]
    )
    actuals_df = (
        actuals.loc[:cutoff]
        .reset_index()
        .rename(columns={"index": "ds", 0: "value"})
        .assign(method="actuals", insample=True)
    )
    future_actuals_df = (
        actuals.loc[cutoff:]
        .reset_index()
        .rename(columns={"index": "ds", 0: "value"})
        .assign(method="actuals", insample=False)
    )
    plot_df = (
        pd.concat([predict_df, actuals_df, future_actuals_df, base_prophet_df])
        .reset_index(drop=True)
        .query(f"ds <= '{plot_cutoff}'")
    )
    sns.pointplot(
        data=plot_df,
        x="ds",
        y="value",
        hue="method",
        style="insample",
        style_order=[True, False],
    )
//  [python]
def plot_forecast(
    actuals: pd.Series,
    predictions: pd.Series,
    cutoff: str,
    events: List[Dict[str, Any]],
):
    """Plot a forecast that's cutoff before actuals finish"""
    base_prophet_df = base_prophet_forecast(
        actuals=actuals, cutoff=cutoff, events=events
    )
    # Find cutoff date for plot
    plot_cutoff = min(
        [base_prophet_df.ds.max(), actuals.index.max(), predictions.index.max()]
    )
    predict_df = (
        predictions.reset_index()
        .rename(columns={"index": "ds", "forecast": "value"})
        .assign(method="judgyprophet")
        .loc[:, ["ds", "value", "insample", "method"]]
    )
    actuals_df = (
        actuals.loc[:cutoff]
        .reset_index()
        .rename(columns={"index": "ds", 0: "value"})
        .assign(method="actuals", insample=True)
    )
    future_actuals_df = (
        actuals.loc[cutoff:]
        .reset_index()
        .rename(columns={"index": "ds", 0: "value"})
        .assign(method="actuals", insample=False)
    )
    plot_df = (
        pd.concat([predict_df, actuals_df, future_actuals_df, base_prophet_df])
        .reset_index(drop=True)
        .query(f"ds <= '{plot_cutoff}'")
    )
    sns.lineplot(
        data=plot_df,
        x="ds",
        y="value",
        hue="method",
        style="insample",
        style_order=[True, False],
    )
//  [python]
def evolution_over_time(self, column, **kwargs):
        """
        Visualize the evolution over time of a column for all assets in group.

        Parameters:
            - column: The name of the column to visualize.
            - kwargs: Additional keyword arguments to pass down
                      to the plotting function.

        Returns:
            A matplotlib `Axes` object.
        """
        if 'ax' not in kwargs:
            fig, ax = plt.subplots(1, 1, figsize=(10, 4))
        else:
            ax = kwargs.pop('ax')
        return sns.tsplot(
            x=self.data.index,
            y=column,
            condition=self.group_by,
            data=self.data,
            ax=ax,
            **kwargs
        )
//  [python]
def evolution_over_time(self, column, **kwargs):
        """
        Visualize the evolution over time of a column for all assets in group.

        Parameters:
            - column: The name of the column to visualize.
            - kwargs: Additional keyword arguments to pass down
                      to the plotting function.

        Returns:
            A matplotlib `Axes` object.
        """
        if 'ax' not in kwargs:
            fig, ax = plt.subplots(1, 1, figsize=(10, 4))
        else:
            ax = kwargs.pop('ax')
        return sns.lineplot(
            x=self.data.index,
            y=column,
            hue=self.group_by,
            data=self.data,
            ax=ax,
            **kwargs
        )
//  [python]
def plot_correlations(
    ax,
    df,
    x_col,
    y_col,
    hue_col = None,
):
  """Correlation plot annotated with Spearman's r."""
  df = df.dropna(subset=[x_col, y_col])
  sns.scatterplot(
      ax=ax, data=df, x=x_col, y=y_col, hue=hue_col, palette=PALETTE
  )
  xmin, xmax = ax.get_xlim()
  ymin, ymax = ax.get_ylim()
  axmin, axmax = min(xmin, ymin), max(xmax, ymax)
  ax.plot([axmin, axmax], [axmin, axmax], color='k', linestyle='--')

  ax.set_ylim(axmin, axmax)
  ax.set_xlim(axmin, axmax)

  ax.set_aspect('equal', adjustable='box')
  corr, _ = scipy.stats.spearmanr(df[x_col], df[y_col])
  ax.annotate(rf'$\rho$ = {corr:.2f}', xy=(0.04, 0.9), xycoords='axes fraction')
  ax.legend(
      bbox_to_anchor=(0.5, 1.1),
      ncol=4,
      loc='center',
      frameon=False,
  )
  return ax
//  [python]
def plot_correlations(
    ax,
    df,
    x_col,
    y_col,
    hue_col = None,
):
  """Correlation plot annotated with Spearman's r."""
  df = df.dropna(subset=[x_col, y_col])
  sns.scatterplot(
      ax=ax, data=df, x=x_col, y=y_col, hue=hue_col, palette=PALETTE
  )
  xmin, xmax = ax.get_xlim()
  ymin, ymax = ax.get_ylim()
  axmin, axmax = min(xmin, ymin), max(xmax, ymax)
  sns.lineplot(
      ax=ax, x=[axmin, axmax], y=[axmin, axmax], color='k', linestyle='--'
  )

  ax.set_ylim(axmin, axmax)
  ax.set_xlim(axmin, axmax)

  ax.set_aspect('equal', adjustable='box')
  corr, _ = scipy.stats.spearmanr(df[x_col], df[y_col])
  ax.annotate(rf'$\rho$ = {corr:.2f}', xy=(0.04, 0.9), xycoords='axes fraction')
  ax.legend(
      bbox_to_anchor=(0.5, 1.1),
      ncol=4,
      loc='center',
      frameon=False,
  )
  return ax
//  [python]
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

# use lineplot that has average curve (for same x-value) with 95% confidence interval on y-value
# https://seaborn.pydata.org/generated/seaborn.lineplot.html
# has at most 3 independent dims to plot, using hue and style. But recommend to use at most 2 dims,
# 	by setting hue and style the same key
# NOTE: any seaborn function has argument ax to support subplots

df_ours = df.loc[df["method"] == "ours"]
ax_id = 0
for key in key_of_interests:
    for variant_tag_name in FLAGS.factors:
        sns.tsplot(
            ax=axes[ax_id],
            data=df_ours,
            time=x_tag,
            value=key,
            unit="method",
            condition=variant_tag_name,
            color=variant_colors[variant_tag_name]
            if variant_tag_name != "Len"
            else None,
            # hue=variant_tag_name,
            # hue_order=order,
            # style=variant_tag,
            # style_order=order,
            # ci=None, # save a lot time without error bars
            #sort=False,
        )
        # the follow command will remove the legend hue, why?
        axes[ax_id].legend(framealpha=0.5, loc="upper left")
        axes[ax_id].set_title(variant_tag_name)

        # if FLAGS.max_x is not None:
        #     axes[ax_id].set_xlim(0, FLAGS.max_x)
        ax_id += 1
//  [python]
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

# use lineplot that has average curve (for same x-value) with 95% confidence interval on y-value
# https://seaborn.pydata.org/generated/seaborn.lineplot.html
# has at most 3 independent dims to plot, using hue and style. But recommend to use at most 2 dims,
# 	by setting hue and style the same key
# NOTE: any seaborn function has argument ax to support subplots

df_ours = df.loc[df["method"] == "ours"]
ax_id = 0
for key in key_of_interests:
    for variant_tag_name in FLAGS.factors:
        sns.lineplot(
            ax=axes[ax_id],
            data=df_ours,
            x=x_tag,
            y=key,
            palette=variant_colors[variant_tag_name]
            if variant_tag_name != "Len"
            else None,
            hue=variant_tag_name,
            # hue_order=order,
            # style=variant_tag,
            # style_order=order,
            # ci=None, # save a lot time without error bars
            sort=False,
        )
        # the follow command will remove the legend hue, why?
        axes[ax_id].legend(framealpha=0.5, loc="upper left")
        axes[ax_id].set_title(variant_tag_name)

        # if FLAGS.max_x is not None:
        #     axes[ax_id].set_xlim(0, FLAGS.max_x)
        ax_id += 1
//  [python]
def plot_train_valid_loss(save_dir):
    train_loss = pd.read_csv(save_dir + "train_log.csv")
    valid_loss = pd.read_csv(save_dir + "valid_log.csv")
    sns.pointplot(x="epoch",y="loss" , data = train_loss, label="train loss")
    sns.pointplot(x="epoch",y="loss" , data = valid_loss, label="valid loss")
    plt.title("epoch vs train loss vs valid loss")
    plt.legend()
    plt.savefig(save_dir+"train_valid_loss.png")
    plt.show()
    print("plot done")
//  [python]
def plot_train_valid_loss(save_dir):
    train_loss = pd.read_csv(save_dir + "train_log.csv")
    valid_loss = pd.read_csv(save_dir + "valid_log.csv")
    sns.lineplot(x="epoch",y="loss" , data = train_loss, label="train loss")
    sns.lineplot(x="epoch",y="loss" , data = valid_loss, label="valid loss")
    plt.title("epoch vs train loss vs valid loss")
    plt.legend()
    plt.savefig(save_dir+"train_valid_loss.png")
    plt.show()
    print("plot done")
//  [python]
def line_chart():
	# 数据准备
	x = [1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910]
	y = [265, 323, 136, 220, 305, 350, 419, 450, 560, 720, 830]
	# 使用Matplotlib画折线图
	plt.plot(x, y)
	plt.show()
	# 使用Seaborn画折线图
	df = pd.DataFrame({'x': x, 'y': y})
	sns.pointplot(x="x", y="y", data=df)
	plt.show()
//  [python]
def line_chart():
	# 数据准备
	x = [1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910]
	y = [265, 323, 136, 220, 305, 350, 419, 450, 560, 720, 830]
	# 使用Matplotlib画折线图
	plt.plot(x, y)
	plt.show()
	# 使用Seaborn画折线图
	df = pd.DataFrame({'x': x, 'y': y})
	sns.lineplot(x="x", y="y", data=df)
	plt.show()
//  [python]
plt.show()

# 条形图
sns.barplot(x='value', y='category', data=df)
plt.title('Bar Chart')
plt.show()

# 区域图
sns.pointplot(x='date', y='value', hue='category', data=df)
//  [python]
plt.show()

# 条形图
sns.barplot(x='value', y='category', data=df)
plt.title('Bar Chart')
plt.show()

# 区域图
sns.lineplot(x='date', y='value', hue='category', data=df)
//  [python]
def plot_accuracy_epoch(accuracy_train,accuracy_test):

    plt.figure(figsize=(12,7))
    plt.title("Train and Test Accuracy in ResNet")
    plt.plot(accuracy_train,label="Training accuracy",color='blue')
    plt.plot(accuracy_test,label="Test Accuracy Model",color='red')
    plt.xlabel("Epochs")    
    plt.ylabel("Accuracy")
    plt.savefig('accuracy.png')
    plt.show()
    return
//  [python]
def plot_accuracy_epoch(accuracy_train,accuracy_test):

    plt.figure(figsize=(12,7))
    plt.title("Train and Test Accuracy in ResNet")
    sns.lineplot(data = accuracy_train,label="Training accuracy",palette="muted")
    sns.lineplot(data = accuracy_test,label="Test Accuracy Model",palette="Dark")
    plt.xlabel("Epochs")    
    plt.ylabel("Accuracy")
    plt.savefig('accuracy.png')
    plt.show()
    return
//  [python]
def plot_loss_epoch(loss_train,loss_test):

    plt.figure(figsize=(12,7))
    plt.title("Train and Test Loss in ResNet")
    plt.plot(loss_train,label="Training Loss")
    plt.plot(loss_test,label="Test Loss")
    plt.xlabel("Epochs")    
    plt.ylabel("Loss")
    plt.show()
    plt.savefig('loss.png')
    return
//  [python]
def plot_loss_epoch(loss_train,loss_test):

    plt.figure(figsize=(12,7))
    plt.title("Train and Test Loss in ResNet")
    sns.lineplot(data = loss_train,label="Training Loss",palette="muted")
    sns.lineplot(data = loss_test,label="Test Loss",palette="dark")
    plt.xlabel("Epochs")    
    plt.ylabel("Loss")
    plt.show()
    plt.savefig('loss.png')
    return
//  [python]
def plot_add_s(ax, metrics, object_name, label):
    thresholds = np.linspace(0.0, 0.1, 1000)
    x_range = thresholds.max() - thresholds.min()
    results = np.array([m['add_s'] for m in metrics])
    accuracies = [(results <= t).sum() / len(results) for t in thresholds]
    auc = sklearn.metrics.auc(thresholds, accuracies) / x_range
    ax = sns.plt.plot(thresholds, accuracies, label=f"{label} ({auc:.04f})", ax=ax)
    ax.set_ylim(0, 1.0)
    ax.set_title(f"{object_name} ADD-S")
    ax.set_ylabel('Accuracy')
    ax.set_xlabel('Threshold (m)')

    return auc
//  [python]
def plot_add_s(ax, metrics, object_name, label):
    thresholds = np.linspace(0.0, 0.1, 1000)
    x_range = thresholds.max() - thresholds.min()
    results = np.array([m['add_s'] for m in metrics])
    accuracies = [(results <= t).sum() / len(results) for t in thresholds]
    auc = sklearn.metrics.auc(thresholds, accuracies) / x_range
    ax = sns.lineplot(thresholds, accuracies, label=f"{label} ({auc:.04f})", ax=ax)
    ax.set_ylim(0, 1.0)
    ax.set_title(f"{object_name} ADD-S")
    ax.set_ylabel('Accuracy')
    ax.set_xlabel('Threshold (m)')

    return auc
//  [python]
def plot_add(ax, metrics, metric_type, object_name, label):
    thresholds = np.linspace(0.0, 0.10, 1000)
    x_range = thresholds.max() - thresholds.min()
    results = np.array([m[metric_type] for m in metrics])
    accuracies = [(results <= t).sum() / len(results) for t in thresholds]
    auc = sklearn.metrics.auc(thresholds, accuracies) / x_range

    ax = sns.plt.plot(thresholds, accuracies, label=f"{label} ({auc:.04f})", ax=ax)
    ax.set_title(f"{object_name} {metric_type}")
    ax.set_ylim(0, 1.0)
    ax.set_ylabel('Accuracy')
    ax.set_xlabel('Threshold (m)')

    return auc
//  [python]
def plot_add(ax, metrics, metric_type, object_name, label):
    thresholds = np.linspace(0.0, 0.10, 1000)
    x_range = thresholds.max() - thresholds.min()
    results = np.array([m[metric_type] for m in metrics])
    accuracies = [(results <= t).sum() / len(results) for t in thresholds]
    auc = sklearn.metrics.auc(thresholds, accuracies) / x_range

    ax = sns.lineplot(thresholds, accuracies, label=f"{label} ({auc:.04f})", ax=ax)
    ax.set_title(f"{object_name} {metric_type}")
    ax.set_ylim(0, 1.0)
    ax.set_ylabel('Accuracy')
    ax.set_xlabel('Threshold (m)')

    return auc
//  [python]
def plot_proj2d(ax, metrics, object_name, label):
    thresholds = np.linspace(0, 40.0, 1000)
    x_range = thresholds.max() - thresholds.min()
    results = np.array([m['proj2d'] for m in metrics])
    accuracies = [(results <= t).sum() / len(results) for t in thresholds]
    auc = sklearn.metrics.auc(thresholds, accuracies) / x_range
    ax = sns.plt.plot(thresholds, accuracies, label=f"{label} ({auc:.04f})", ax=ax)
    ax.set_ylim(0, 1.0)
    ax.set_title(f"{object_name} Proj. 2D")
    ax.set_ylabel('Accuracy')
    ax.set_xlabel('Threshold (px)')

    return auc
//  [python]
def plot_proj2d(ax, metrics, object_name, label):
    thresholds = np.linspace(0, 40.0, 1000)
    x_range = thresholds.max() - thresholds.min()
    results = np.array([m['proj2d'] for m in metrics])
    accuracies = [(results <= t).sum() / len(results) for t in thresholds]
    auc = sklearn.metrics.auc(thresholds, accuracies) / x_range
    ax = sns.lineplot(thresholds, accuracies, label=f"{label} ({auc:.04f})", ax=ax)
    ax.set_ylim(0, 1.0)
    ax.set_title(f"{object_name} Proj. 2D")
    ax.set_ylabel('Accuracy')
    ax.set_xlabel('Threshold (px)')

    return auc
//  [python]
def price_graph(self, monthsback: int = 6) -> tuple:
        """Display this symbol's price graph over the last monthsback months.

        Returns from_date, fig, and ax in order for subclass functions to add to the
        information and even the graph displayed here.
        """
        fig, ax = plt.subplots(figsize=(16, 8))
        hist = self.price_history().df

        # Calc start date:
        from_date = datetime.date.today() - pd.offsets.DateOffset(months=monthsback)
        from_date = from_date.strftime("%Y-%m-%d")

        # Plot the prices:
        ax.plot(hist.loc[from_date:, "close"], marker="o")
        ax.set(title=self.name)

        return from_date, fig, ax
//  [python]
def price_graph(self, monthsback: int = 6) -> tuple:
        """Display this symbol's price graph over the last monthsback months.

        Returns from_date, fig, and ax in order for subclass functions to add to the
        information and even the graph displayed here.
        """
        fig, ax = plt.subplots(figsize=(16, 8))
        hist = self.price_history().df

        # Calc start date:
        from_date = datetime.date.today() - pd.offsets.DateOffset(months=monthsback)
        from_date = from_date.strftime("%Y-%m-%d")

        # Plot the prices:
        sns.lineplot(ax=ax, data=hist.loc[from_date:, "close"], marker="o").set(
            title=self.name
        )

        return from_date, fig, ax
//  [python]
sns.relplot(data = tips,
             x = "size",
             y = "tip",
             kind = "scatter")

sns.pointplot(data = tips,
             x = "size",
             y = "tip")
//  [python]
sns.relplot(data = tips,
             x = "size",
             y = "tip",
             kind = "line")

#%% Joining combining the two doesn't work!
sns.relplot(data = tips,
             x = "size",
             y = "tip",
             kind = "scatter")

sns.relplot(data = tips,
             x = "size",
             y = "tip",
             kind = "line")

#%% But using sns.lineplot() makes the second graph on the same figure
sns.relplot(data = tips,
             x = "size",
             y = "tip",
             kind = "scatter")

sns.lineplot(data = tips,
             x = "size",
             y = "tip")
//  [python]
def main(statsfile1, statsfile2, iterations, outfile=None):
    df1 = parse_stats_file(statsfile1)
    df2 = parse_stats_file(statsfile2)

    df = pandas.DataFrame.merge(
        df1, df2, on=["kind", "batchsize"], how="outer", suffixes=["_before", "_after"]
    )
    df["ratio"] = df["ms_after"] / df["ms_before"]

    df_melted = pandas.melt(
        df, id_vars=["kind", "batchsize"], value_vars=["ms_before", "ms_after"]
    )

    fig, ax = plt.subplots(nrows=3, figsize=(16, 16))

    seaborn.pointplot(
        x="batchsize",
        y="value",
        hue="variable",
        data=df_melted.where(df_melted["kind"] == KIND),
        ax=ax[0],
    ).set(
        title=f"Mean execution time by batch size (concretized), its={iterations}",
        ylabel="milliseconds",
        ylim=(0, 1),
    )

    df["ms_before"] = df["ms_before"] * df["batchsize"]
    df["ms_after"] = df["ms_after"] * df["batchsize"]

    df_melted = pandas.melt(
        df, id_vars=["kind", "batchsize"], value_vars=["ms_before", "ms_after"]
    )

    seaborn.pointplot(
        x="batchsize",
        y="value",
        hue="variable",
        data=df_melted.where(df_melted["kind"] == KIND),
        ax=ax[1],
    ).set(
        title=f"Total execution time by batch size (concretized), its={iterations}",
        ylabel="milliseconds",
        ylim=(0, 10),
    )

    df_melted = pandas.melt(df, id_vars=["kind", "batchsize"], value_vars=["ratio"])
    seaborn.barplot(
        x="batchsize",
        y="value",
        hue="variable",
        data=df_melted.where(df_melted["kind"] == KIND),
        ax=ax[2],
    ).set(
        title=f"Relative improvement",
        ylabel="Relative speed",
        ylim=(0.6, 1.4),
    )

    # print(df.where(df["partition"] == "before")["ms"])
    # r = (
    #     df.where(df["partition"] == "before")["ms"]
    #     / df.where(df["partition"] == "after")["ms"]
    # )
    # print(r)
    # seaborn.lineplot(x=list(range(1, 25)), y=r, data=df, ax=ax[2],).set(
    #     title=f"Total execution time by batch size (concretized), its={iterations}",
    #     ylabel="milliseconds",
    #     ylim=(0, 10),
    # )

    if outfile:
        plt.savefig(outfile)

    else:
        plt.show()
//  [python]
def main(statsfile1, statsfile2, iterations, outfile=None):
    df1 = parse_stats_file(statsfile1)
    df2 = parse_stats_file(statsfile2)

    df = pandas.DataFrame.merge(
        df1, df2, on=["kind", "batchsize"], how="outer", suffixes=["_before", "_after"]
    )
    df["ratio"] = df["ms_after"] / df["ms_before"]

    df_melted = pandas.melt(
        df, id_vars=["kind", "batchsize"], value_vars=["ms_before", "ms_after"]
    )

    fig, ax = plt.subplots(nrows=3, figsize=(16, 16))

    seaborn.lineplot(
        x="batchsize",
        y="value",
        hue="variable",
        data=df_melted.where(df_melted["kind"] == KIND),
        ax=ax[0],
    ).set(
        title=f"Mean execution time by batch size (concretized), its={iterations}",
        ylabel="milliseconds",
        ylim=(0, 1),
    )

    df["ms_before"] = df["ms_before"] * df["batchsize"]
    df["ms_after"] = df["ms_after"] * df["batchsize"]

    df_melted = pandas.melt(
        df, id_vars=["kind", "batchsize"], value_vars=["ms_before", "ms_after"]
    )

    seaborn.lineplot(
        x="batchsize",
        y="value",
        hue="variable",
        data=df_melted.where(df_melted["kind"] == KIND),
        ax=ax[1],
    ).set(
        title=f"Total execution time by batch size (concretized), its={iterations}",
        ylabel="milliseconds",
        ylim=(0, 10),
    )

    df_melted = pandas.melt(df, id_vars=["kind", "batchsize"], value_vars=["ratio"])
    seaborn.barplot(
        x="batchsize",
        y="value",
        hue="variable",
        data=df_melted.where(df_melted["kind"] == KIND),
        ax=ax[2],
    ).set(
        title=f"Relative improvement",
        ylabel="Relative speed",
        ylim=(0.6, 1.4),
    )

    # print(df.where(df["partition"] == "before")["ms"])
    # r = (
    #     df.where(df["partition"] == "before")["ms"]
    #     / df.where(df["partition"] == "after")["ms"]
    # )
    # print(r)
    # seaborn.lineplot(x=list(range(1, 25)), y=r, data=df, ax=ax[2],).set(
    #     title=f"Total execution time by batch size (concretized), its={iterations}",
    #     ylabel="milliseconds",
    #     ylim=(0, 10),
    # )

    if outfile:
        plt.savefig(outfile)

    else:
        plt.show()
//  [python]
def plot_experiment_logs(fname: str, paths, tags=None):
    if tags is None:
        tags = paths
    dfs = [pd.read_csv(path) for path in paths]
    for tag, df in zip(tags, dfs):
        for col in df.columns:
            df[col] = [float(x[7:-1]) for x in df[col]]
        df["Tag"] = [tag] * df.shape[0]
        df["Epoch"] = list(range(df.shape[0]))
    df = pd.concat(dfs)

    ncol = 3
    nrow = math.ceil((len(df.columns) - 1) / ncol)
    fig, axs = plt.subplots(nrow, ncol, figsize=(20, 15))
    i = 0
    for col in df.columns:
        if col == "Epoch" or col == "Tag":
            continue
        sns.tsplot(
            x="Epoch",
            y=col,
            data=df,
            ax=axs[i // ncol][i % ncol],
            condition="Tag",
        )
        i += 1

    plt.tight_layout()
    plt.savefig(fname)
//  [python]
def plot_experiment_logs(fname: str, paths, tags=None):
    if tags is None:
        tags = paths
    dfs = [pd.read_csv(path) for path in paths]
    for tag, df in zip(tags, dfs):
        for col in df.columns:
            df[col] = [float(x[7:-1]) for x in df[col]]
        df["Tag"] = [tag] * df.shape[0]
        df["Epoch"] = list(range(df.shape[0]))
    df = pd.concat(dfs)

    ncol = 3
    nrow = math.ceil((len(df.columns) - 1) / ncol)
    fig, axs = plt.subplots(nrow, ncol, figsize=(20, 15))
    i = 0
    for col in df.columns:
        if col == "Epoch" or col == "Tag":
            continue
        sns.lineplot(
            x="Epoch",
            y=col,
            data=df,
            ax=axs[i // ncol][i % ncol],
            hue="Tag",
        )
        i += 1

    plt.tight_layout()
    plt.savefig(fname)
//  [python]
def visualise_results(self, kind="line") -> None:
        """Plot the results of the experiment. Shows the observed rewards over
        timesteps, the distribution of observed rewards for each arm and the
        number of times each arm was drawn.

        Args:
            kind (str, optional): Plot to draw for the observed reward. One of
                ['line', 'scatter']. Defaults to "line".
        """
        fig, ax = plt.subplots(figsize=(15, 10), nrows=3, ncols=1)

        reward_df = pd.DataFrame(
            {
                "timestep": range(len(self.observed_rewards)),
                "reward_raw": self.observed_rewards,
            }
        )
        reward_df["reward"] = reward_df["reward_raw"].rolling(10).mean()

        if kind == "line":
            sns.pointplot(data=reward_df, x="timestep", y="reward", ax=ax[0], join=True)
        else:
            sns.scatterplot(
                data=reward_df, x="timestep", y="reward_raw", hue="reward_raw", ax=ax[0]
            )
        ax[0].set_title("Reward observed at each timestep")

        sns.violinplot(
            x=self.observed_draws, y=self.observed_rewards, width=0.5, ax=ax[1]
        )
        ax[1].set_ylabel("observed reward")
        ax[1].set_xlabel("arm")
        ax[1].set_title("Distribution of observed rewards for each arm")

        arms, counts = np.unique(self.observed_draws, return_counts=True)
        sns.scatterplot(x=arms, y=counts, ax=ax[2])
        ax[2].set_ylim(0, len(self.observed_rewards))
        ax[2].set_ylabel("number of draws")
        ax[2].set_xlabel("arm")
        ax[2].set_title("Number of draws of each arm")

        fig.tight_layout()
        plt.show()
//  [python]
def visualise_results(self, kind="line") -> None:
        """Plot the results of the experiment. Shows the observed rewards over
        timesteps, the distribution of observed rewards for each arm and the
        number of times each arm was drawn.

        Args:
            kind (str, optional): Plot to draw for the observed reward. One of
                ['line', 'scatter']. Defaults to "line".
        """
        fig, ax = plt.subplots(figsize=(15, 10), nrows=3, ncols=1)

        reward_df = pd.DataFrame(
            {
                "timestep": range(len(self.observed_rewards)),
                "reward_raw": self.observed_rewards,
            }
        )
        reward_df["reward"] = reward_df["reward_raw"].rolling(10).mean()

        if kind == "line":
            sns.lineplot(data=reward_df, x="timestep", y="reward", ax=ax[0])
        else:
            sns.scatterplot(
                data=reward_df, x="timestep", y="reward_raw", hue="reward_raw", ax=ax[0]
            )
        ax[0].set_title("Reward observed at each timestep")

        sns.violinplot(
            x=self.observed_draws, y=self.observed_rewards, width=0.5, ax=ax[1]
        )
        ax[1].set_ylabel("observed reward")
        ax[1].set_xlabel("arm")
        ax[1].set_title("Distribution of observed rewards for each arm")

        arms, counts = np.unique(self.observed_draws, return_counts=True)
        sns.scatterplot(x=arms, y=counts, ax=ax[2])
        ax[2].set_ylim(0, len(self.observed_rewards))
        ax[2].set_ylabel("number of draws")
        ax[2].set_xlabel("arm")
        ax[2].set_title("Number of draws of each arm")

        fig.tight_layout()
        plt.show()
//  [python]
def calibrate(abt_node_df: pd.DataFrame, variables: list[str] = None):
    """Calibrate the ABT node given in abd_node_df with the given model input variables."""
    # pylint: disable=invalid-name
    if variables is None:
        variables = ['n_processed']
    y = abt_node_df['execution_time']
    X = abt_node_df[variables]
    X = sm.add_constant(X)

    nnls = LinearRegression(positive=True, fit_intercept=False)
    model = nnls.fit(X, y)
    y_pred = model.predict(X)
    print(f'R2: {r2_score(y, y_pred)}')
    print(f'Coefficients: {model.coef_}')

    sns.scatterplot(x=abt_node_df['n_processed'], y=abt_node_df['execution_time'])
    sns.regplot(x=abt_node_df['n_processed'], y=y_pred, color='red')
//  [python]
def calibrate(abt_node_df: pd.DataFrame, variables: list[str] = None):
    """Calibrate the ABT node given in abd_node_df with the given model input variables."""
    # pylint: disable=invalid-name
    if variables is None:
        variables = ['n_processed']
    y = abt_node_df['execution_time']
    X = abt_node_df[variables]
    X = sm.add_constant(X)

    nnls = LinearRegression(positive=True, fit_intercept=False)
    model = nnls.fit(X, y)
    y_pred = model.predict(X)
    print(f'R2: {r2_score(y, y_pred)}')
    print(f'Coefficients: {model.coef_}')

    sns.scatterplot(x=abt_node_df['n_processed'], y=abt_node_df['execution_time'])
    sns.lineplot(x=abt_node_df['n_processed'], y=y_pred, color='red')
//  [python]
def main():
    plt.figure()

    for client_num in client_num_list:
        plt.figure
        plt.title(f"{client_num} client experiments")
        # add event files
        data = {"Config": [], "Round": [], "AUC": []}
        # add centralized result
        eventfile = glob.glob(centralized_path, recursive=True)
        assert len(eventfile) == 1, "No unique event file found!" + eventfile
        eventfile = eventfile[0]
        print("adding", eventfile)
        add_eventdata(data, "centralized", eventfile, tag="AUC")
        # pick first client for bagging experiments
        site = 1
        for config, exp in experiments_bagging[client_num].items():
            record_path = os.path.join(client_results_root + config, "simulate_job", client_pre + str(site), "events.*")
            eventfile = glob.glob(record_path, recursive=True)
            assert len(eventfile) == 1, "No unique event file found!"
            eventfile = eventfile[0]
            print("adding", eventfile)
            add_eventdata(data, config, eventfile, tag=exp["tag"])

        # Combine all clients' records for cyclic experiments
        for site in range(1, client_num + 1):
            for config, exp in experiments_cyclic[client_num].items():
                record_path = os.path.join(
                    client_results_root + config, "simulate_job", client_pre + str(site), "events.*"
                )
                eventfile = glob.glob(record_path, recursive=True)
                assert len(eventfile) == 1, f"No unique event file found under {record_path}!"
                eventfile = eventfile[0]
                print("adding", eventfile)
                add_eventdata(data, config, eventfile, tag=exp["tag"])

        plt.plot( 'Round', 'AUC', data=data, linestyle='-', marker='o')
        plt.show()
//  [python]
def main():
    plt.figure()

    for client_num in client_num_list:
        plt.figure
        plt.title(f"{client_num} client experiments")
        # add event files
        data = {"Config": [], "Round": [], "AUC": []}
        # add centralized result
        eventfile = glob.glob(centralized_path, recursive=True)
        assert len(eventfile) == 1, "No unique event file found!" + eventfile
        eventfile = eventfile[0]
        print("adding", eventfile)
        add_eventdata(data, "centralized", eventfile, tag="AUC")
        # pick first client for bagging experiments
        site = 1
        for config, exp in experiments_bagging[client_num].items():
            record_path = os.path.join(client_results_root + config, "simulate_job", client_pre + str(site), "events.*")
            eventfile = glob.glob(record_path, recursive=True)
            assert len(eventfile) == 1, "No unique event file found!"
            eventfile = eventfile[0]
            print("adding", eventfile)
            add_eventdata(data, config, eventfile, tag=exp["tag"])

        # Combine all clients' records for cyclic experiments
        for site in range(1, client_num + 1):
            for config, exp in experiments_cyclic[client_num].items():
                record_path = os.path.join(
                    client_results_root + config, "simulate_job", client_pre + str(site), "events.*"
                )
                eventfile = glob.glob(record_path, recursive=True)
                assert len(eventfile) == 1, f"No unique event file found under {record_path}!"
                eventfile = eventfile[0]
                print("adding", eventfile)
                add_eventdata(data, config, eventfile, tag=exp["tag"])

        sns.lineplot(x="Round", y="AUC", hue="Config", data=data)
        plt.show()
//  [python]
def plot_average(
        self,
        event_type,
        center="Peak",
        hue="Channel",
        time_before=1,
        time_after=1,
        filt=(None, None),
        mask=None,
        figsize=(6, 4.5),
        **kwargs,
    ):
        """Plot the average event (not for REM, spindles & SW only)"""
        import seaborn as sns
        import matplotlib.pyplot as plt

        df_sync = self.get_sync_events(
            center=center, time_before=time_before, time_after=time_after, filt=filt, mask=mask
        )
        assert not df_sync.empty, "Could not calculate event-locked data."
        assert hue in ["Stage", "Channel"], "hue must be 'Channel' or 'Stage'"
        assert hue in df_sync.columns, "%s is not present in data." % hue

        if event_type == "spindles":
            title = "Average spindle"
        else:  # "sw":
            title = "Average SW"

        # Start figure
        fig, ax = plt.subplots(1, 1, figsize=figsize)
        sns.tsplot(data=df_sync, time="Time", value="Amplitude", unit="Trial", condition=hue, ax=ax, **kwargs)
        # ax.legend(frameon=False, loc='lower right')
        ax.set_xlim(df_sync["Time"].min(), df_sync["Time"].max())
        ax.set_title(title)
        ax.set_xlabel("Time (sec)")
        ax.set_ylabel("Amplitude (uV)")
        return ax