jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def _output_graph(self, agg_data: List[Sequence[Number]], num_runs: int):
    """Builds a graph of the results and outputs to a .png.

    Args:
      agg_data: 2d array of data to be graphed.
      num_runs: Number of columns of runs in the data.
    """
    # Build data frames
    columns = ['step']
    columns.extend([str(i) for i in range(num_runs)])
    # csv contains aggregate info that will get excluded in the pd.melt.
    columns.extend(['median', 'mean'])
    print(columns)
    df = pd.DataFrame(agg_data, columns=columns)
    logging.debug('Dataframes datatypes: %s', df.dtypes)
    new_pd = pd.melt(
        df,
        id_vars='step',
        value_vars=list(df.columns[1 : num_runs + 1]),
        var_name='run',
        value_name=self.yaxis_title,
    )
    logging.info('DataFrame to graph:\n%s', new_pd)
    # Build graph
    plt.figure(figsize=(10, 5))
    ax = sns.lineplot(
        data=new_pd, x='step', y=self.yaxis_title, estimator=self.graph_agg
    )
    ax.set_title(self.title)
    ax.set(xlabel=self.xaxis_title)
    plt.ticklabel_format(style='plain', axis='x')
    graph_path = os.path.join(
        self.output_path, self.output_prefix + '_graph.png'
    )
    plt.savefig(graph_path)
//  [python]
def solution_plot(self):
        self._view.solution()
        plt.figure(figsize=(16,6))
        sns.tsplot(data=df)
//  [python]
def solution_plot(self):
        self._view.solution()
        plt.figure(figsize=(16,6))
        sns.lineplot(data=df)
//  [python]
def save_as_plot(self, save_dir, title=""):
        sns.set_theme(style="darkgrid")
        data = self.df.rename_axis('epochs')
        for column in self.columns:
            plot = sns.tsplot(data=data, time="epochs", value=column, unit="exp_name",
                                color='pastel', legend="full")
            save_dir_ = os.path.join(save_dir, f'{column}.png')
            plot.get_figure().savefig(save_dir_)
            plot.get_figure().clf()
            log.info(f"Result pack has been saved as a figure to: {save_dir_}")
//  [python]
def save_as_plot(self, save_dir, title=""):
        sns.set_theme(style="darkgrid")
        data = self.df.rename_axis('epochs')
        for column in self.columns:
            plot = sns.lineplot(data=data, x="epochs", y=column, hue='exp_name',
                                palette='pastel', legend="full")
            save_dir_ = os.path.join(save_dir, f'{column}.png')
            plot.get_figure().savefig(save_dir_)
            plot.get_figure().clf()
            log.info(f"Result pack has been saved as a figure to: {save_dir_}")
//  [python]
def plot_fitted(
        self, 
        models="all",
        exclude = [], 
        order_by=None, 
        ax = None,
        figsize=(12,6),
    ):
        """ Plots all fitted values with the actuals. Does not support level fitted values (for now).

        Args:
            models (list-like,str): Default 'all'.
               The forecated models to plot.
               Can start with "top_" and the metric specified in order_by will be used to order the models appropriately.
            exclude (collection): Default []. Pass any models here that you don't want displayed.
                Good to use in conjunction with models = 'top_{n}'. 
            order_by (str): Optional. One of Forecaster.determine_best_by.
                How to order the display of forecasts on the plots (from best-to-worst according to the selected metric).
            ax (Axis): Optional. The existing axis to write the resulting figure to.
            figsize (tuple): Default (12,6). Size of the resulting figure. Ignored when ax is not None.

        Returns:
            (Axis): The figure's axis.

        >>> models = ('mlr','mlp','lightgbm')
        >>> f.tune_test_forecast(models,dynamic_testing=False,feature_importance=True)
        >>> f.plot_fitted(order_by='TestSetRMSE') # plots all fitted values
        >>> plt.show()
        """
        if ax is None:
            _, ax = plt.subplots(figsize=figsize)

        models = [m for m in self._parse_models(models, order_by) if m not in exclude]
        dates = self.current_dates.values
        actuals = self.y.values

        plot = {
            "date": dates,
            "actuals": actuals,
        }
        plt.plot(plot["date"], plot["actuals"], label="actuals")

        for i, m in enumerate(models):
            plot[m] = (self.history[m]["FittedVals"])
            if plot[m] is None or not len(plot[m]):
                continue
            plt.plot(
                plot["date"][-len(plot[m]) :],
                plot[m][-len(plot["date"]) :],
                linestyle="--",
                color=__colors__[i],
                alpha=0.7,
                label=m,
            )

        ax.legend()
        ax.set_xlabel("Date")
        ax.set_ylabel("Values")
        return ax
//  [python]
def plot_fitted(
        self, 
        models="all",
        exclude = [], 
        order_by=None, 
        ax = None,
        figsize=(12,6),
    ):
        """ Plots all fitted values with the actuals. Does not support level fitted values (for now).

        Args:
            models (list-like,str): Default 'all'.
               The forecated models to plot.
               Can start with "top_" and the metric specified in order_by will be used to order the models appropriately.
            exclude (collection): Default []. Pass any models here that you don't want displayed.
                Good to use in conjunction with models = 'top_{n}'. 
            order_by (str): Optional. One of Forecaster.determine_best_by.
                How to order the display of forecasts on the plots (from best-to-worst according to the selected metric).
            ax (Axis): Optional. The existing axis to write the resulting figure to.
            figsize (tuple): Default (12,6). Size of the resulting figure. Ignored when ax is not None.

        Returns:
            (Axis): The figure's axis.

        >>> models = ('mlr','mlp','lightgbm')
        >>> f.tune_test_forecast(models,dynamic_testing=False,feature_importance=True)
        >>> f.plot_fitted(order_by='TestSetRMSE') # plots all fitted values
        >>> plt.show()
        """
        if ax is None:
            _, ax = plt.subplots(figsize=figsize)

        models = [m for m in self._parse_models(models, order_by) if m not in exclude]
        dates = self.current_dates.values
        actuals = self.y.values

        plot = {
            "date": dates,
            "actuals": actuals,
        }
        sns.lineplot(x=plot["date"], y=plot["actuals"], label="actuals", ax=ax)

        for i, m in enumerate(models):
            plot[m] = (self.history[m]["FittedVals"])
            if plot[m] is None or not len(plot[m]):
                continue
            sns.lineplot(
                x=plot["date"][-len(plot[m]) :],
                y=plot[m][-len(plot["date"]) :],
                linestyle="--",
                color=__colors__[i],
                alpha=0.7,
                label=m,
                ax=ax,
            )

        ax.legend()
        ax.set_xlabel("Date")
        ax.set_ylabel("Values")
        return ax
//  [python]
def plot_probabilities(self, dataframe, name, exponential):
        """
        Sets chart parameters, generates the chart, and saves it.
        
        dataframe: dataframe, the dataframe to be plotted
        
        name: sting, chart title
        
        exponential: boolean, whether to plot exponentially weighted output data or not
        """
        dataframe.rename(columns=self.prediction_names, inplace=True)
        if exponential == True:
            dataframe = self.exponential_conversion(dataframe=dataframe)
        is_recession = dataframe['Recession'] == 1
        is_not_recession = dataframe['Recession'] == 0
        dataframe.loc[is_recession, 'Recession'] = 100
        dataframe.loc[is_not_recession, 'Recession'] = -1
        dataframe = dataframe[['Dates'] + list(self.prediction_names.values())]
        
        plt.figure(figsize=(15, 5))
        plot = sns.tsplot(x='Dates', y='value', unit='variable',
                            data=pd.melt(dataframe, ['Dates']))
        plot.set_ylabel('Probability')
        plot.set_title(name, fontsize = 20)
        plot.set_ylim((0, 1))
        self.pdf_object.savefig()
//  [python]
def plot_probabilities(self, dataframe, name, exponential):
        """
        Sets chart parameters, generates the chart, and saves it.
        
        dataframe: dataframe, the dataframe to be plotted
        
        name: sting, chart title
        
        exponential: boolean, whether to plot exponentially weighted output data or not
        """
        dataframe.rename(columns=self.prediction_names, inplace=True)
        if exponential == True:
            dataframe = self.exponential_conversion(dataframe=dataframe)
        is_recession = dataframe['Recession'] == 1
        is_not_recession = dataframe['Recession'] == 0
        dataframe.loc[is_recession, 'Recession'] = 100
        dataframe.loc[is_not_recession, 'Recession'] = -1
        dataframe = dataframe[['Dates'] + list(self.prediction_names.values())]
        
        plt.figure(figsize=(15, 5))
        plot = sns.lineplot(x='Dates', y='value', hue='variable',
                            data=pd.melt(dataframe, ['Dates']))
        plot.set_ylabel('Probability')
        plot.set_title(name, fontsize = 20)
        plot.set_ylim((0, 1))
        self.pdf_object.savefig()
//  [python]
def plot(x_c, y_c, x_t, y_t, idx, title, preds, pad_val=None, conf=None):
    y_c = y_c[..., idx]
    y_t = y_t[..., idx]
    preds = preds[..., idx]

    if pad_val is not None:
        y_c = y_c[y_c != pad_val]
        yt_mask = y_t != pad_val
        y_t = y_t[yt_mask]
        preds = preds[yt_mask]

    fig, ax = plt.subplots(figsize=(7, 4))
    xaxis_c = np.arange(len(y_c))
    xaxis_t = np.arange(len(y_c), len(y_c) + len(y_t))
    context = pd.DataFrame({"xaxis_c": xaxis_c, "y_c": y_c})
    target = pd.DataFrame({"xaxis_t": xaxis_t, "y_t": y_t, "pred": preds})
    plt.plot(context["xaxis_c"], context["y_c"], label="Context", linewidth=5.8)
    ax.scatter(
        x=target["xaxis_t"], y=target["y_t"], c="grey", label="True", linewidth=1.0
    )
    plt.plot(target["xaxis_t"], target["pred"], label="Forecast", linewidth=5.9)
    if conf is not None:
        conf = conf[..., idx]
        ax.fill_between(
            xaxis_t, (preds - conf), (preds + conf), color="orange", alpha=0.1
        )
    ax.legend(loc="upper left", prop={"size": 12})
    # ax.set_facecolor("#f0f0f0")
    ax.set_xticks([])
    ax.set_xlabel("")
    ax.set_ylabel("")
    ax.set_title(title)

    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=128)
    buf.seek(0)
    img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
    buf.close()
    plt.close(fig)
    img = cv2.imdecode(img_arr, 1)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return img
//  [python]
def plot(x_c, y_c, x_t, y_t, idx, title, preds, pad_val=None, conf=None):
    y_c = y_c[..., idx]
    y_t = y_t[..., idx]
    preds = preds[..., idx]

    if pad_val is not None:
        y_c = y_c[y_c != pad_val]
        yt_mask = y_t != pad_val
        y_t = y_t[yt_mask]
        preds = preds[yt_mask]

    fig, ax = plt.subplots(figsize=(7, 4))
    xaxis_c = np.arange(len(y_c))
    xaxis_t = np.arange(len(y_c), len(y_c) + len(y_t))
    context = pd.DataFrame({"xaxis_c": xaxis_c, "y_c": y_c})
    target = pd.DataFrame({"xaxis_t": xaxis_t, "y_t": y_t, "pred": preds})
    sns.lineplot(data=context, x="xaxis_c", y="y_c", label="Context", linewidth=5.8)
    ax.scatter(
        x=target["xaxis_t"], y=target["y_t"], c="grey", label="True", linewidth=1.0
    )
    sns.lineplot(data=target, x="xaxis_t", y="pred", label="Forecast", linewidth=5.9)
    if conf is not None:
        conf = conf[..., idx]
        ax.fill_between(
            xaxis_t, (preds - conf), (preds + conf), color="orange", alpha=0.1
        )
    ax.legend(loc="upper left", prop={"size": 12})
    # ax.set_facecolor("#f0f0f0")
    ax.set_xticks([])
    ax.set_xlabel("")
    ax.set_ylabel("")
    ax.set_title(title)

    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=128)
    buf.seek(0)
    img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
    buf.close()
    plt.close(fig)
    img = cv2.imdecode(img_arr, 1)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return img
//  [python]
def dual_axis_ts_plot(
    df,
    var1,
    var2,
    date_col,
    fig_width=25,
    fig_height=6,
    path=None,
    color1=palette.OrbitPalette.BLACK.value,
    color2=palette.OrbitPalette.BLUE.value,
):
    """This function plots two time series variables on two y axis. This is handy for comparison of two variables. The dual
    y axis will set on two different scales if the two variables are very different in terms of volume.
    Parameters
    -----------
    df : pandas data frame
        input df
    var1 : str
        name of the first variable
    var2 : str
        name of the second variable
    date_col : str
        date column name
    fig_width : int, optional
        adjust width of the chart
    fig_height : int, optional,
        adjust height of the chart
    path : str
        path to save the figure
    color1: str
        color for var1
    color2: str
        color for var2

    Returns
    -------
    one time series plot with dual y axis
    """
    df[date_col] = pd.to_datetime(df[date_col])
    fig, ax = plt.subplots(figsize=(fig_width, fig_height))
    plt.plot(df[date_col],df[var1], label=var1, color=color1)
    ax.set_ylabel(f"{var1}", color=color1)
    ax.tick_params(axis="y", labelcolor=color1)
    ax2 = ax.twinx()
    plt.plot(df[date_col],df[var2], ax=ax2, color=color2, label=var2)
    ax2.set_ylabel(f"{var2}", color=color2)
    ax2.tick_params(axis="y", labelcolor=color2)
    lines, labels = ax.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    ax2.legend(lines + lines2, labels + labels2, loc=0)
    ax.set_title(f"{var1} vs {var2}")
    # ax.grid(False)
    ax2.grid(False)

    if path:
        fig.savefig(path)

    return ax
//  [python]
def dual_axis_ts_plot(
    df,
    var1,
    var2,
    date_col,
    fig_width=25,
    fig_height=6,
    path=None,
    color1=palette.OrbitPalette.BLACK.value,
    color2=palette.OrbitPalette.BLUE.value,
):
    """This function plots two time series variables on two y axis. This is handy for comparison of two variables. The dual
    y axis will set on two different scales if the two variables are very different in terms of volume.
    Parameters
    -----------
    df : pandas data frame
        input df
    var1 : str
        name of the first variable
    var2 : str
        name of the second variable
    date_col : str
        date column name
    fig_width : int, optional
        adjust width of the chart
    fig_height : int, optional,
        adjust height of the chart
    path : str
        path to save the figure
    color1: str
        color for var1
    color2: str
        color for var2

    Returns
    -------
    one time series plot with dual y axis
    """
    df[date_col] = pd.to_datetime(df[date_col])
    fig, ax = plt.subplots(figsize=(fig_width, fig_height))
    sns.lineplot(data=df, x=date_col, y=var1, label=var1, color=color1)
    ax.set_ylabel(f"{var1}", color=color1)
    ax.tick_params(axis="y", labelcolor=color1)
    ax2 = ax.twinx()
    sns.lineplot(data=df, x=date_col, y=var2, ax=ax2, color=color2, label=var2)
    ax2.set_ylabel(f"{var2}", color=color2)
    ax2.tick_params(axis="y", labelcolor=color2)
    lines, labels = ax.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    ax2.legend(lines + lines2, labels + labels2, loc=0)
    ax.set_title(f"{var1} vs {var2}")
    # ax.grid(False)
    ax2.grid(False)

    if path:
        fig.savefig(path)

    return ax
//  [python]
def lineplot(data, *args, **kwargs):
    return s.lineplot(data, *args, **kwargs)
//  [python]
def lineplot(data, *args, **kwargs):
    return sns.lineplot(data, *args, **kwargs)
//  [python]
for row in g.axes:
    for ax in row:
        ax.set_ylabel('Mean Stability (%)')
        ax.set_xlabel('Iterative Pruning Rate (% and Log Scale)')
g.axes[0][0].set_xticklabels([2**x for x in range(0,8)])
ax_ins = inset_axes(g.axes[0][0],
                    width="54.3%", 
                    height="55%", 
                    loc="center",bbox_to_anchor=(-.037, -.05, 1, 1),
                      bbox_transform=g.axes[0][0].transAxes)
ax_ins.set_ylim(98.65,100)
s.lineplot('Iterative_Pruned_Percent',
                   'Stability', hue = 'Pruning Style', legend=False,
                  hue_order=['Prune_S', 'Prune_R', 'Prune_L'], markers=True,
                  style='Pruning Style',
                  data=data.query("Retrain<72").query("pruned_epoch==True").groupby(
        ['Retrain', 'Pruning Style', 'Iterative_Pruned_Percent','run']
        ).mean().Stability.reset_index(), ax=ax_ins)
//  [python]
for row in g.axes:
    for ax in row:
        ax.set_ylabel('Mean Stability (%)')
        ax.set_xlabel('Iterative Pruning Rate (% and Log Scale)')
g.axes[0][0].set_xticklabels([2**x for x in range(0,8)])
ax_ins = inset_axes(g.axes[0][0],
                    width="54.3%", 
                    height="55%", 
                    loc="center",bbox_to_anchor=(-.037, -.05, 1, 1),
                      bbox_transform=g.axes[0][0].transAxes)
ax_ins.set_ylim(98.65,100)
sns.lineplot('Iterative_Pruned_Percent',
                   'Stability', hue = 'Pruning Style', legend=False,
                  hue_order=['Prune_S', 'Prune_R', 'Prune_L'], markers=True,
                  style='Pruning Style',
                  data=data.query("Retrain<72").query("pruned_epoch==True").groupby(
        ['Retrain', 'Pruning Style', 'Iterative_Pruned_Percent','run']
        ).mean().Stability.reset_index(), ax=ax_ins)
//  [python]
def plot_5_countries_4_regions(X, yl):
    fig, axes = plt.subplots(ncols=4, figsize=(18, 5))
    for a, region in zip(axes, countries):
        for country in countries[region]:
            s.lineplot(data=X.loc[country], label=country, ax=a)
        a.plot([0, 55], [0, 0], 'k--')
        a.legend()
        a.xaxis.set_major_locator(plt.MaxNLocator(10))
        a.set_xlabel("Date")
        a.set_ylabel(yl)
        a.set_title(region)

    plt.tight_layout()
    plt.show()
//  [python]
def plot_5_countries_4_regions(X, yl):
    fig, axes = plt.subplots(ncols=4, figsize=(18, 5))
    for a, region in zip(axes, countries):
        for country in countries[region]:
            sns.lineplot(data=X.loc[country], label=country, ax=a)
        a.plot([0, 55], [0, 0], 'k--')
        a.legend()
        a.xaxis.set_major_locator(plt.MaxNLocator(10))
        a.set_xlabel("Date")
        a.set_ylabel(yl)
        a.set_title(region)

    plt.tight_layout()
    plt.show()
//  [python]
def plot_reward(save_dir, varname, ylabel, save_fig=False):
    fig, ax = plt.subplots(1, 1, figsize=(7, 4))
    #
    sns.tsplot(data=data[varname].dropna(), ax=ax)
    plt.xlabel("Training Iterations")
    plt.title(ylabel + " (ppo)")
    if save_fig:
        plt.savefig(save_dir + "/" + ylabel + ".png")
//  [python]
def plot_reward(save_dir, varname, ylabel, save_fig=False):
    fig, ax = plt.subplots(1, 1, figsize=(7, 4))
    #
    sns.lineplot(data=data[varname].dropna(), ax=ax)
    plt.xlabel("Training Iterations")
    plt.title(ylabel + " (ppo)")
    if save_fig:
        plt.savefig(save_dir + "/" + ylabel + ".png")
//  [python]
def scatterplot(x: np.array, y: np.array, filename: str, xlabel: str, ylabel: str, xlim: Optional[Tuple[float, float]]=None, ylim: Optional[Tuple[float, float]]=None, calibration_line: bool=False):
  sns.scatterplot(x=x, y=y, color='coral')
  if calibration_line: plt.plot(np.arange(xlim[0], xlim[1]), np.arange(ylim[0], ylim[1]), color='gray', linestyle='--')

  plt.xticks(fontsize=14)
  plt.yticks(fontsize=14)
  plt.xlabel(xlabel, fontsize=16)
  plt.ylabel(ylabel, fontsize=16)
  plt.xlim(*xlim) if xlim is not None else plt.margins(x=0)
  plt.ylim(*ylim) if ylim is not None else plt.margins(y=0)
  plt.tight_layout()
  plt.savefig(f'results/{filename}.png')
  plt.close()
//  [python]
def scatterplot(x: np.array, y: np.array, filename: str, xlabel: str, ylabel: str, xlim: Optional[Tuple[float, float]]=None, ylim: Optional[Tuple[float, float]]=None, calibration_line: bool=False):
  sns.scatterplot(x=x, y=y, color='coral')
  if calibration_line: sns.lineplot(x=np.arange(xlim[0], xlim[1]), y=np.arange(ylim[0], ylim[1]), color='gray', linestyle='--')

  plt.xticks(fontsize=14)
  plt.yticks(fontsize=14)
  plt.xlabel(xlabel, fontsize=16)
  plt.ylabel(ylabel, fontsize=16)
  plt.xlim(*xlim) if xlim is not None else plt.margins(x=0)
  plt.ylim(*ylim) if ylim is not None else plt.margins(y=0)
  plt.tight_layout()
  plt.savefig(f'results/{filename}.png')
  plt.close()
//  [python]
def vis_curves(curves, names):
    import matplotlib.pyplot as plt
    import seaborn as sns
    df_cm = pd.DataFrame(np.vstack(curves).T, columns=names, index=np.arange(1, len(curves[0])+1))

    plt.figure(figsize=(20,20))

    sns.tsplot(data=np.array(curves).T, condition=names)
    return plt
//  [python]
def vis_curves(curves, names):
    import matplotlib.pyplot as plt
    df_cm = pd.DataFrame(np.vstack(curves).T, columns=names, index=np.arange(1, len(curves[0])+1))

    plt.figure(figsize=(20,20))

    sns.lineplot(data=df_cm)
    return plt
//  [python]
def plot_mortality(df, title='Mortality', size=1):
    f, ax = plt.subplots(1,1, figsize=(4*size,2*size))
    g = sns.pointplot(x="Date", y='Mortality (Deaths/Cases)', data=df, color='blue', label='Mortality (Deaths / Total Cases)')
    plt.xlabel('Date')
    plt.ylabel(f'Mortality {title} [%]')
    plt.xticks(rotation=90)
    plt.title(f'Mortality percent {title}\nCalculated as Deaths/Confirmed cases')
    ax.grid(color='black', linestyle='dashed', linewidth=1)
    plt.show()
//  [python]
def plot_mortality(df, title='Mortality', size=1):
    f, ax = plt.subplots(1,1, figsize=(4*size,2*size))
    g = sns.lineplot(x="Date", y='Mortality (Deaths/Cases)', data=df, color='blue', label='Mortality (Deaths / Total Cases)')
    plt.xlabel('Date')
    plt.ylabel(f'Mortality {title} [%]')
    plt.xticks(rotation=90)
    plt.title(f'Mortality percent {title}\nCalculated as Deaths/Confirmed cases')
    ax.grid(color='black', linestyle='dashed', linewidth=1)
    plt.show()
//  [python]
def plot():
    try:
        import seaborn as sns
        import numpy as np
        import matplotlib.pyplot as plt
    except ModuleNotFoundError:
        return

    fig, ax = plt.subplots(figsize=(1, 2))
    df = sns.load_dataset("penguins")

    sns.displot(
        df, x="flipper_length_mm", col="species", row="sex",
        binwidth=3, height=3, facet_kws=dict(margin_titles=True),
    )

    # sns.histplot(
    #     df, x="flipper_length_mm"
    # )

    sns.pointplot(data=df, x="flipper_length_mm", y="flipper_length_mm")
    sns.lmplot(data=df, x="flipper_length_mm", y="flipper_length_mm")
    sns.scatterplot(data=df, x="flipper_length_mm", y="flipper_length_mm")

    sns.catplot(
        data=df, kind="bar",
        x="species", y="body_mass_g", hue="sex",
        ci="sd", palette="dark", alpha=.6, height=6
    )

    x = np.array(list("ABCDEFGHIJ"))
    y1 = np.arange(1, 11)
    sns.barplot(x=x, y=y1, palette="rocket", ax=ax)

    sns.violinplot(data=df, palette="Set3", bw=.2, cut=1, linewidth=1)

    flights_long = sns.load_dataset("flights")
    flights = flights_long.pivot("month", "year", "passengers")
    sns.heatmap(flights, annot=True, fmt="d", linewidths=.5, ax=ax)

    tips = sns.load_dataset("tips")
    sns.boxplot(x="day", y="total_bill",
                hue="smoker", palette=["m", "g"],
                data=tips)
    sns.despine(offset=10, trim=True)

    import matplotlib.pyplot as plt

    plt.show()
//  [python]
def plot():
    try:
        import seaborn as sns
        import numpy as np
        import matplotlib.pyplot as plt
    except ModuleNotFoundError:
        return

    fig, ax = plt.subplots(figsize=(1, 2))
    df = sns.load_dataset("penguins")

    sns.displot(
        df, x="flipper_length_mm", col="species", row="sex",
        binwidth=3, height=3, facet_kws=dict(margin_titles=True),
    )

    # sns.histplot(
    #     df, x="flipper_length_mm"
    # )

    sns.lineplot(data=df, x="flipper_length_mm", y="flipper_length_mm")
    sns.lmplot(data=df, x="flipper_length_mm", y="flipper_length_mm")
    sns.scatterplot(data=df, x="flipper_length_mm", y="flipper_length_mm")

    sns.catplot(
        data=df, kind="bar",
        x="species", y="body_mass_g", hue="sex",
        ci="sd", palette="dark", alpha=.6, height=6
    )

    x = np.array(list("ABCDEFGHIJ"))
    y1 = np.arange(1, 11)
    sns.barplot(x=x, y=y1, palette="rocket", ax=ax)

    sns.violinplot(data=df, palette="Set3", bw=.2, cut=1, linewidth=1)

    flights_long = sns.load_dataset("flights")
    flights = flights_long.pivot("month", "year", "passengers")
    sns.heatmap(flights, annot=True, fmt="d", linewidths=.5, ax=ax)

    tips = sns.load_dataset("tips")
    sns.boxplot(x="day", y="total_bill",
                hue="smoker", palette=["m", "g"],
                data=tips)
    sns.despine(offset=10, trim=True)

    import matplotlib.pyplot as plt

    plt.show()
//  [python]
def plot_data(orig_datas, score_datas, model_names):
    score_datas[0]['model'] = model_names[0]
    score_datas[1]['model'] = model_names[1]
    data = pd.concat(score_datas, ignore_index=True)
    plt.figure(figsize=(6, 4))
    sns.barplot(x='tag', y='score', hue='model', data=data)
    plt.xticks(rotation=90)
    save_plot(f'preds-tag-scores', 'layerwise macro averaged scores per tag')

    for orig_data, score_data, model_name in zip(orig_datas, score_datas, model_names):
        pos_groups = {
            # 'closed classes': ['adp', 'aux', 'cconj', 'det', 'num', 'part', 'pron', 'sconj'],
            'closed classes': ['pron', 'det', 'sconj', 'aux'],
            # 'closed classes (2/2)': ['num', 'adp', 'cconj', 'part'],
            'open classes': ['adj', 'adv', 'intj', 'noun', 'propn', 'verb'],
            'open classes w/o verb': ['adj', 'adv', 'intj', 'noun', 'propn'],
            'other': ['num', 'adp', 'cconj', 'punct', 'sym', 'x']
        }

        plt.figure(figsize=(6, 4))
        sns.pointplot(x='layer', y='score', hue='tag', data=score_data)
        save_plot(f'preds-tags-layer-changes-{model_name}', 'F1 scores per POS tag per layer')

        plt.figure(figsize=(6, 4))
        sns.pointplot(x='layer', y='score', data=score_data)
        save_plot(f'preds-macro-layer-changes-{model_name}', 'Macro averaged F1 scores per layer')

        for name, items in pos_groups.items():
            slug = name.replace(' ', '_').replace('2)', '').replace('/', '').replace('(', '')

            group_data = score_data[score_data['tag'].isin(items)]
            plt.figure(figsize=(6, 4))
            sns.pointplot(x='layer', y='score', hue='tag', data=group_data)
            save_plot(f'preds-tags-layer-changes-{model_name}-{slug}',
                      f'F1 scores per POS tag per layer for {name}')

            plt.figure(figsize=(6, 4))
            sns.pointplot(x='layer', y='score', data=group_data)
            save_plot(f'preds-macro-layer-changes-{model_name}-{slug}',
                      f'Macro averaged F1 scores per layer for {name}')
//  [python]
def plot_data(orig_datas, score_datas, model_names):
    score_datas[0]['model'] = model_names[0]
    score_datas[1]['model'] = model_names[1]
    data = pd.concat(score_datas, ignore_index=True)
    plt.figure(figsize=(6, 4))
    sns.barplot(x='tag', y='score', hue='model', data=data)
    plt.xticks(rotation=90)
    save_plot(f'preds-tag-scores', 'layerwise macro averaged scores per tag')

    for orig_data, score_data, model_name in zip(orig_datas, score_datas, model_names):
        pos_groups = {
            # 'closed classes': ['adp', 'aux', 'cconj', 'det', 'num', 'part', 'pron', 'sconj'],
            'closed classes': ['pron', 'det', 'sconj', 'aux'],
            # 'closed classes (2/2)': ['num', 'adp', 'cconj', 'part'],
            'open classes': ['adj', 'adv', 'intj', 'noun', 'propn', 'verb'],
            'open classes w/o verb': ['adj', 'adv', 'intj', 'noun', 'propn'],
            'other': ['num', 'adp', 'cconj', 'punct', 'sym', 'x']
        }

        plt.figure(figsize=(6, 4))
        sns.lineplot(x='layer', y='score', hue='tag', data=score_data)
        save_plot(f'preds-tags-layer-changes-{model_name}', 'F1 scores per POS tag per layer')

        plt.figure(figsize=(6, 4))
        sns.lineplot(x='layer', y='score', data=score_data)
        save_plot(f'preds-macro-layer-changes-{model_name}', 'Macro averaged F1 scores per layer')

        for name, items in pos_groups.items():
            slug = name.replace(' ', '_').replace('2)', '').replace('/', '').replace('(', '')

            group_data = score_data[score_data['tag'].isin(items)]
            plt.figure(figsize=(6, 4))
            sns.lineplot(x='layer', y='score', hue='tag', data=group_data)
            save_plot(f'preds-tags-layer-changes-{model_name}-{slug}',
                      f'F1 scores per POS tag per layer for {name}')

            plt.figure(figsize=(6, 4))
            sns.lineplot(x='layer', y='score', data=group_data)
            save_plot(f'preds-macro-layer-changes-{model_name}-{slug}',
                      f'Macro averaged F1 scores per layer for {name}')
//  [python]
def plot_aggregate_states(df, states, case_type='Total Cases', size=3, is_log=False):
    f, ax = plt.subplots(1,1, figsize=(4*size, 3*size))
    for state in states:
        df_ = df[(df['State']==state) & (df['Date'] > '2020-03-01')] 
        g = sns.pointplot(x="Date", y=case_type, data=df_,  label=state)  
        ax.text(max(df_['Date']), max(df_[case_type]), str(state))
    plt.xlabel('Date')
    plt.ylabel(f' {case_type} ')
    plt.title(f' {case_type} ')
    plt.xticks(rotation=90)
    if(is_log):
        ax.set(yscale="log")
    ax.grid(color='black', linestyle='dotted', linewidth=0.75)
    plt.show()
//  [python]
def plot_aggregate_states(df, states, case_type='Total Cases', size=3, is_log=False):
    f, ax = plt.subplots(1,1, figsize=(4*size, 3*size))
    for state in states:
        df_ = df[(df['State']==state) & (df['Date'] > '2020-03-01')] 
        g = sns.lineplot(x="Date", y=case_type, data=df_,  label=state)  
        ax.text(max(df_['Date']), max(df_[case_type]), str(state))
    plt.xlabel('Date')
    plt.ylabel(f' {case_type} ')
    plt.title(f' {case_type} ')
    plt.xticks(rotation=90)
    if(is_log):
        ax.set(yscale="log")
    ax.grid(color='black', linestyle='dotted', linewidth=0.75)
    plt.show()
//  [python]
def plot_relative_error(data_dir="heterogeneous_example_data"):
    if data_dir[-1] != "/":
        data_dir += "/"
    data_filename = data_dir + "heterogeneous_example_error_data.json"
    data = json.load(open(data_filename))

    plotting_data = []
    for n in data.keys():
        for i in data[n].keys():
            d = {"Sample Size": int(n), "Iteration": int(i)}
            true_effects = data[n][str(i)]["true_effects"]
            estimated_effects = data[n][str(i)]["estimated_effects"]
            error = np.array(true_effects) - np.array(estimated_effects)
            relative_error = np.linalg.norm(error) / np.linalg.norm(true_effects)
            d["Relative Error"] = relative_error
            plotting_data.append(d)
    plotting_df = pd.DataFrame(plotting_data)

    plt.figure(figsize=(18, 8))
    ax = plt.gca()
    grid = sns.pointplot(
        x="Sample Size", y="Relative Error", data=plotting_df, ax=ax
    )
    sample_sizes = [int(n) for n in data.keys()]
    ax.set_xticks(sample_sizes)
    ax.set_xticklabels([""] + sample_sizes[1:], rotation=45)
    ax.set_xlim([0, max(sample_sizes) + 100])
    sns.despine()
    plt.title("Relative Error of Causal Forest")
    plt.show()
//  [python]
def plot_relative_error(data_dir="heterogeneous_example_data"):
    if data_dir[-1] != "/":
        data_dir += "/"
    data_filename = data_dir + "heterogeneous_example_error_data.json"
    data = json.load(open(data_filename))

    plotting_data = []
    for n in data.keys():
        for i in data[n].keys():
            d = {"Sample Size": int(n), "Iteration": int(i)}
            true_effects = data[n][str(i)]["true_effects"]
            estimated_effects = data[n][str(i)]["estimated_effects"]
            error = np.array(true_effects) - np.array(estimated_effects)
            relative_error = np.linalg.norm(error) / np.linalg.norm(true_effects)
            d["Relative Error"] = relative_error
            plotting_data.append(d)
    plotting_df = pd.DataFrame(plotting_data)

    plt.figure(figsize=(18, 8))
    ax = plt.gca()
    grid = sns.lineplot(
        x="Sample Size", y="Relative Error", data=plotting_df, marker="o", ax=ax
    )
    sample_sizes = [int(n) for n in data.keys()]
    ax.set_xticks(sample_sizes)
    ax.set_xticklabels([""] + sample_sizes[1:], rotation=45)
    ax.set_xlim([0, max(sample_sizes) + 100])
    sns.despine()
    plt.title("Relative Error of Causal Forest")
    plt.show()
//  [python]
def get_df_with_coin_price_volatility(data: pd.DataFrame, display_plot: bool):
    """
    Unify volatility values for each coin and plot the graph.

    Parameters: DataFrame with computed volatility, boolean value to plot the graph
    """
    vix_df = data.groupby(
        ["currency_pair", pd.Grouper(key="date", freq=frequency)]
    )["close"].mean()
    vix_df = vix_df.to_frame()
    vix_df.columns = ["ema_volatility"]
    if display_plot:
        sns.set(rc={"figure.figsize": (15, 8)})
        sns.tsplot(
            data=vix_df, time="date", value="ema_volatility", unit="currency_pair"
        ).set(title=f"EMA of Volatility for each coin")
    return vix_df
//  [python]
def get_df_with_coin_price_volatility(data: pd.DataFrame, display_plot: bool):
    """
    Unify volatility values for each coin and plot the graph.

    Parameters: DataFrame with computed volatility, boolean value to plot the graph
    """
    vix_df = data.groupby(
        ["currency_pair", pd.Grouper(key="date", freq=frequency)]
    )["close"].mean()
    vix_df = vix_df.to_frame()
    vix_df.columns = ["ema_volatility"]
    if display_plot:
        sns.set(rc={"figure.figsize": (15, 8)})
        sns.lineplot(
            data=vix_df, x="date", y="ema_volatility", hue="currency_pair"
        ).set(title=f"EMA of Volatility for each coin")
    return vix_df
//  [python]
def test_DecisionMatrixPlotter_frontier(fig_test, fig_ref, strict):
    dm = mkdm(
        matrix=[
            [0.65229926, 0.04377532],
            [0.02002959, 0.83921258],
            [0.58714305, 0.22470523],
        ],
        objectives=[min, max],
        weights=[0.41997791, 0.45103139],
        alternatives=["A0", "A1", "A2"],
        criteria=["C0", "C1"],
    )

    x, y = dm.criteria

    plotter = plot.DecisionMatrixPlotter(dm=dm)

    test_ax = fig_test.subplots()
    plotter.frontier(x=x, y=y, strict=strict, ax=test_ax)

    # EXPECTED
    exp_ax = fig_ref.subplots()

    # scatter
    sdm = dm[[x, y]]
    df = sdm.matrix

    sns.scatterplot(x=x, y=y, data=df, hue=df.index, ax=exp_ax)

    # frontier
    non_dominated = pd.DataFrame(
        [
            [0.65229926, 0.83921258],
            [0.02002959, 0.83921258],
            [0.02002959, 0.04377532],
        ],
        columns=pd.Index(["C0", "C1"], name="Criteria"),
    )

    sns.lineplot(
        x=x,
        y=y,
        data=non_dominated,
        estimator=None,
        sort=False,
        ax=exp_ax,
        alpha=0.5,
        linestyle="-" if strict else "--",
        label="Strict frontier" if strict else "Frontier",
    )

    exp_ax.set_xlabel(f"{x} {dm.objectives[x].to_symbol()}")
    exp_ax.set_ylabel(f"{y} {dm.objectives[y].to_symbol()}")

    handles, labels = exp_ax.get_legend_handles_labels()
    exp_ax.legend(handles, labels, title="Alternatives")
//  [python]
y_array = np.array([])
x_array = np.array([])
rs = np.random.RandomState(8)
for _ in range(15):
    x = np.linspace(0, 30 / 2, 30)
    y = np.sin(x) + rs.normal(0, 1.5) + rs.normal(0, 0.3, 30)
    y_array = np.append(y_array, y)
    x_array = np.append(x_array, x)

# Plot the average over replicates with confidence interval
sns.tsplot(y=y_array, x=x_array)
//  [python]
y_array = np.array([])
x_array = np.array([])
rs = np.random.RandomState(8)
for _ in range(15):
    x = np.linspace(0, 30 / 2, 30)
    y = np.sin(x) + rs.normal(0, 1.5) + rs.normal(0, 0.3, 30)
    y_array = np.append(y_array, y)
    x_array = np.append(x_array, x)

# Plot the average over replicates with confidence interval
sns.lineplot(y=y_array, x=x_array)
//  [python]
def main():
    import argparse
    import seaborn as sns
    import matplotlib.pyplot as plt
    parser = argparse.ArgumentParser()
    parser.add_argument('time', help="Path to numpy file with times")
    parser.add_argument('labels', help="Path to numpy file with labels")
    parser.add_argument('--t_start', default=None, type=int, help="Start time")
    parser.add_argument('--history', default=None, type=int, help="Sliding window size for previous labels")
    parser.add_argument('--cumulative', default=False, action='store_true', help="Apply history also to 'right-side'")
    parser.add_argument('--save_plot', default=None, type=str, help="Path to save plot")
    parser.add_argument('--info', default=False, action='store_true', help="Print some more info")
    args = parser.parse_args()
    verbose = args.info

    time = np.load(args.time)
    labels = np.load(args.labels)
    if verbose:
        print("Time shape", time.shape, "dtype", time.dtype)
        print("Labels shape", labels.shape, "dtype", labels.dtype)

    x, y = drift_magnitude_per_time(time, labels, t_start=args.t_start, verbose=verbose,
            history=args.history, cumulative=args.cumulative)

    sns.tsplot(x=x,y=y)
    if args.save_plot:
        plt.savefig(args.save_plot)
    else:
        plt.show()
//  [python]
def main():
    import argparse
    import seaborn
    import matplotlib.pyplot as plt
    parser = argparse.ArgumentParser()
    parser.add_argument('time', help="Path to numpy file with times")
    parser.add_argument('labels', help="Path to numpy file with labels")
    parser.add_argument('--t_start', default=None, type=int, help="Start time")
    parser.add_argument('--history', default=None, type=int, help="Sliding window size for previous labels")
    parser.add_argument('--cumulative', default=False, action='store_true', help="Apply history also to 'right-side'")
    parser.add_argument('--save_plot', default=None, type=str, help="Path to save plot")
    parser.add_argument('--info', default=False, action='store_true', help="Print some more info")
    args = parser.parse_args()
    verbose = args.info

    time = np.load(args.time)
    labels = np.load(args.labels)
    if verbose:
        print("Time shape", time.shape, "dtype", time.dtype)
        print("Labels shape", labels.shape, "dtype", labels.dtype)

    x, y = drift_magnitude_per_time(time, labels, t_start=args.t_start, verbose=verbose,
            history=args.history, cumulative=args.cumulative)

    seaborn.lineplot(x=x,y=y)
    if args.save_plot:
        plt.savefig(args.save_plot)
    else:
        plt.show()
//  [python]
def dist(args):
    """
    %prog dist input.dist.npy genome.json

    Plot histogram based on .dist.npy data file. The .npy file stores an array
    with link counts per dist bin, with the bin starts stored in the genome.json.
    """
    import seaborn as sns
    import pandas as pd
    from jcvi.graphics.base import human_base_formatter, markup

    p = OptionParser(dist.__doc__)
    p.add_argument("--title", help="Title of the histogram")
    p.add_argument("--xmin", default=300, help="Minimum distance")
    p.add_argument("--xmax", default=6000000, help="Maximum distance")
    opts, args, iopts = p.set_image_options(args, figsize="6x6")

    if len(args) != 2:
        sys.exit(not p.print_help())

    npyfile, jsonfile = args
    pf = npyfile.rsplit(".", 1)[0]
    header = json.loads(open(jsonfile).read())
    distbin_starts = np.array(header["distbinstarts"], dtype="float64")
    distbin_sizes = np.array(header["distbinsizes"], dtype="float64")
    a = np.load(npyfile)

    xmin, xmax = opts.xmin, opts.xmax
    df = pd.DataFrame()
    xstart, xend = (
        np.searchsorted(distbin_starts, xmin),
        np.searchsorted(distbin_starts, xmax),
    )
    df["BinStart"] = distbin_starts[xstart:xend]
    df["LinkDensity"] = a[xstart:xend] / distbin_sizes[xstart:xend]
    ax = sns.plt.plot(
        df["BinStart"], df["LinkDensity"], lw=3, color="lightslategray"
    )
    tx = df["BinStart"]
    A, B, label = fit_power_law(tx, df["LinkDensity"])
    ty = A * tx**B
    ax = sns.plt.plot(tx, ty, "r:", lw=3, label=label)
    ax.legend()
    if opts.title:
        ax.set_title(markup(opts.title))
    ax.set_xlabel("Link size (bp)")
    ax.set_ylabel(r"Density (\# of links per bp)")
    ax.set_xscale("log", nonposx="clip")
    ax.set_yscale("log", nonposy="clip")
    ax.xaxis.set_major_formatter(human_base_formatter)

    image_name = pf + "." + opts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
//  [python]
def dist(args):
    """
    %prog dist input.dist.npy genome.json

    Plot histogram based on .dist.npy data file. The .npy file stores an array
    with link counts per dist bin, with the bin starts stored in the genome.json.
    """
    import seaborn as sns
    import pandas as pd
    from jcvi.graphics.base import human_base_formatter, markup

    p = OptionParser(dist.__doc__)
    p.add_argument("--title", help="Title of the histogram")
    p.add_argument("--xmin", default=300, help="Minimum distance")
    p.add_argument("--xmax", default=6000000, help="Maximum distance")
    opts, args, iopts = p.set_image_options(args, figsize="6x6")

    if len(args) != 2:
        sys.exit(not p.print_help())

    npyfile, jsonfile = args
    pf = npyfile.rsplit(".", 1)[0]
    header = json.loads(open(jsonfile).read())
    distbin_starts = np.array(header["distbinstarts"], dtype="float64")
    distbin_sizes = np.array(header["distbinsizes"], dtype="float64")
    a = np.load(npyfile)

    xmin, xmax = opts.xmin, opts.xmax
    df = pd.DataFrame()
    xstart, xend = (
        np.searchsorted(distbin_starts, xmin),
        np.searchsorted(distbin_starts, xmax),
    )
    df["BinStart"] = distbin_starts[xstart:xend]
    df["LinkDensity"] = a[xstart:xend] / distbin_sizes[xstart:xend]
    ax = sns.lineplot(
        x="BinStart", y="LinkDensity", data=df, lw=3, color="lightslategray"
    )
    tx = df["BinStart"]
    A, B, label = fit_power_law(tx, df["LinkDensity"])
    ty = A * tx**B
    ax.plot(tx, ty, "r:", lw=3, label=label)
    ax.legend()
    if opts.title:
        ax.set_title(markup(opts.title))
    ax.set_xlabel("Link size (bp)")
    ax.set_ylabel(r"Density (\# of links per bp)")
    ax.set_xscale("log", nonposx="clip")
    ax.set_yscale("log", nonposy="clip")
    ax.xaxis.set_major_formatter(human_base_formatter)

    image_name = pf + "." + opts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
//  [python]
iterations = np.arange(1,steps+1)
ax = plt.gca()
plt.ylim(0,1)
ax.fill_between(iterations, mus + stds, mus - stds, alpha=.25)
plt.plot(iterations, mus, ax=ax)
//  [python]
iterations = np.arange(1,steps+1)
ax = plt.gca()
plt.ylim(0,1)
ax.fill_between(iterations, mus + stds, mus - stds, alpha=.25)
sns.lineplot(iterations, mus, ax=ax)
//  [python]
def visualise_gradcam(att_maps,
                      median_sample,
                      figsize,
                      cmap,
                      **kwargs):
    matplotlib.use('TKagg')

    if figsize is None:
        figsize = (12, 4)
    if att_maps[0].ndim == 3:
        att_maps[0] = att_maps[0].mean(1)
    if att_maps[1].ndim == 3:
        att_maps[1] = att_maps[1].mean(1)

    idx_plot = list(range(2 + len(median_sample)))
    fig, axs = plt.subplots(
        len(idx_plot), 1, figsize=figsize, sharex=True, **kwargs)
    for idx, class_number in enumerate(median_sample):
        axs[idx].set_title(f'Median sample of {class_number}')
        plt.plot(median_sample[class_number].reshape(-1, 1), ax=axs[idx])
    axs[idx_plot[-2]].set_title('Observed Variables')
    axs[idx_plot[-1]].set_title('Attention by the time')
    sns.heatmap(att_maps[0].numpy(), cbar=False,
                cmap=cmap, ax=axs[idx_plot[-2]])
    sns.heatmap(att_maps[1].numpy(), cbar=False,
                cmap=cmap, ax=axs[idx_plot[-1]])
    fig.tight_layout()
    plt.show()
//  [python]
def visualise_gradcam(att_maps,
                      median_sample,
                      figsize,
                      cmap,
                      **kwargs):
    matplotlib.use('TKagg')

    if figsize is None:
        figsize = (12, 4)
    if att_maps[0].ndim == 3:
        att_maps[0] = att_maps[0].mean(1)
    if att_maps[1].ndim == 3:
        att_maps[1] = att_maps[1].mean(1)

    idx_plot = list(range(2 + len(median_sample)))
    fig, axs = plt.subplots(
        len(idx_plot), 1, figsize=figsize, sharex=True, **kwargs)
    for idx, class_number in enumerate(median_sample):
        axs[idx].set_title(f'Median sample of {class_number}')
        sns.lineplot(median_sample[class_number].reshape(-1, 1), ax=axs[idx])
    axs[idx_plot[-2]].set_title('Observed Variables')
    axs[idx_plot[-1]].set_title('Attention by the time')
    sns.heatmap(att_maps[0].numpy(), cbar=False,
                cmap=cmap, ax=axs[idx_plot[-2]])
    sns.heatmap(att_maps[1].numpy(), cbar=False,
                cmap=cmap, ax=axs[idx_plot[-1]])
    fig.tight_layout()
    plt.show()
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1,
              save=False, **kwargs):
    if smooth > 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="whitegrid", font_scale=1.5*0+2, rc={'axes.grid' : False})
    sns.tsplot(data=data, time=xaxis, value=value, unit=condition, ci='sd', linewidth=3.,
                 palette='colorblind', **kwargs)
    leg = plt.legend(loc='best', fontsize=20)
    for line in leg.get_lines():
        line.set_linewidth(3.)
    leg.set_draggable(True)
    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    plt.tight_layout(pad=0.5)

    if save:
        plt.savefig(value)
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1,
              save=False, **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="whitegrid", font_scale=1.5*0+2, rc={'axes.grid' : False})
    sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', linewidth=3.,
                 palette='colorblind', **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.
    """
    leg = plt.legend(loc='best', fontsize=20)
    for line in leg.get_lines():
        line.set_linewidth(3.)
    leg.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)

    if save:
        plt.savefig(value)