jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def OverheadLinePlot(df,path):
    df2 = df[['Where','Number of Nodes','MPolka CRC8','MPolka CRC16','MPINT','INT Clássico']].copy()
    #Rename Dataframe
    df2.rename(columns = {'MPolka CRC8':'INT-MPolKA (CRC8)', 'MPolka CRC16':'INT-MPolKA (CRC16)','INT Clássico':'INT Original'}, inplace = True)
    #Melting dataframe
    dfm = df2.melt(id_vars=['Where','Number of Nodes'], var_name='Type', value_name='Overhead')
    dfm1 = dfm.loc[dfm['Where'] == 'DataPlane']
    dfm2 = dfm.loc[dfm['Where'] == 'ControlPlane']

    #Extract size of dataframe
    numberOfTopologys = int((len(df2.axes[0]))/2)
    #Plot Config
    f,ax= plt.subplots(2,1,figsize=(10,10),sharex=True)
    #f.suptitle('Overhead (Bytes) (%s Topologys)' %numberOfTopologys)
    ax[0].set_title('DataPlane',fontsize=16)
    ax[1].set_title('ControlPlane',fontsize=16)
    #plt.xlabel('Number of Nodes',fontsize=18)
    #plt.ylabel('Overhead',fontsize=18)
    f.text(0.5, 0.04, 'Number of Nodes', ha='center',fontsize='18')
    f.text(0.04, 0.5, 'Overhead (Bytes)', va='center', rotation='vertical',fontsize='18')
    #Plot Data
    g1 = sns.pointplot(x="Number of Nodes", y="Overhead", hue='Type',ax=ax[0], data=dfm1);
    g1.set(xlabel=None,ylabel=None)
    g2 = sns.pointplot(x="Number of Nodes", y="Overhead", hue='Type',ax=ax[1], data=dfm2);
    g2.set(xlabel=None,ylabel=None)
    #Save Fig
    ov.ensureExist(path)
    plt.savefig(Path(f'{path}/OverheadLP.png'),bbox_inches='tight',pad_inches=0.1,dpi=120)
    plt.savefig(Path(f'{path}/OverheadLP.pdf'),bbox_inches='tight',pad_inches=0.1,dpi=120)
//  [python]
def OverheadLinePlot(df,path):
    df2 = df[['Where','Number of Nodes','MPolka CRC8','MPolka CRC16','MPINT','INT Clássico']].copy()
    #Rename Dataframe
    df2.rename(columns = {'MPolka CRC8':'INT-MPolKA (CRC8)', 'MPolka CRC16':'INT-MPolKA (CRC16)','INT Clássico':'INT Original'}, inplace = True)
    #Melting dataframe
    dfm = df2.melt(id_vars=['Where','Number of Nodes'], var_name='Type', value_name='Overhead')
    dfm1 = dfm.loc[dfm['Where'] == 'DataPlane']
    dfm2 = dfm.loc[dfm['Where'] == 'ControlPlane']

    #Extract size of dataframe
    numberOfTopologys = int((len(df2.axes[0]))/2)
    #Plot Config
    f,ax= plt.subplots(2,1,figsize=(10,10),sharex=True)
    #f.suptitle('Overhead (Bytes) (%s Topologys)' %numberOfTopologys)
    ax[0].set_title('DataPlane',fontsize=16)
    ax[1].set_title('ControlPlane',fontsize=16)
    #plt.xlabel('Number of Nodes',fontsize=18)
    #plt.ylabel('Overhead',fontsize=18)
    f.text(0.5, 0.04, 'Number of Nodes', ha='center',fontsize='18')
    f.text(0.04, 0.5, 'Overhead (Bytes)', va='center', rotation='vertical',fontsize='18')
    #Plot Data
    g1 = sns.lineplot(x="Number of Nodes", y="Overhead", hue='Type',ax=ax[0], data=dfm1,errorbar=None);
    g1.set(xlabel=None,ylabel=None)
    g2 = sns.lineplot(x="Number of Nodes", y="Overhead", hue='Type',ax=ax[1], data=dfm2,errorbar=None);
    g2.set(xlabel=None,ylabel=None)
    #Save Fig
    ov.ensureExist(path)
    plt.savefig(Path(f'{path}/OverheadLP.png'),bbox_inches='tight',pad_inches=0.1,dpi=120)
    plt.savefig(Path(f'{path}/OverheadLP.pdf'),bbox_inches='tight',pad_inches=0.1,dpi=120)
//  [python]
def metric_lineplot(df, predictors, metric, predictor_names, dataset_name,
    max_n_mut, savename='figure', legend=None, mutcounts=None, **kwargs):
    fig, axes = plt.subplots(1, max_n_mut+1,
                             figsize=((max_n_mut+1)*3, 4),
                             sharex=True, sharey=True)
    ax = axes[0]
    nmut_to_title = {
        1: 'Single mutants',
        2: 'Double mutants',
        3: 'Triple mutants',
        4: 'Quadruple mutants',
    }
    nmut_to_title.update({i: f'{i}th-order Mutants' for i in range(5, 11)})
    tmp = retrieve_metric(df, metric, n_mut=None, predictor=predictors)
    sns.tsplot(data=tmp, time='n_train', value='val',
                 unit='predictor', condition='predictor', ax=ax,
                 condition_order=predictors, **kwargs)
    #ax.hlines(df[df.predictor == 'mutation'].mean().spearman, 48, 240, color='dimgrey')
    ax.set_title(f'mutants of all orders')
    ax.set_ylabel(metric_display_name[metric])
    ax.set_xlabel('Training data size')
    for n_mut in range(1, max_n_mut+1):
        ax = axes[n_mut]
        tmp = retrieve_metric(df, metric, n_mut=n_mut, predictor=predictors)
        sns.tsplot(data=tmp, time='n_train', value='val',
                     unit='predictor', condition='predictor', ax=ax,
                     condition_order=predictors, **kwargs)
        ax.set_title(nmut_to_title[n_mut])
        ax.set_ylabel(metric_display_name[metric])
        ax.set_xlabel('Training data size')
    if mutcounts is not None:
        for i in range(max_n_mut+1):
            axes[i].annotate(f'Data size: {int(mutcounts[i])}',
                xy=(0.29, 0.03), xycoords='axes fraction', 
                fontsize=9)

    if legend is not None:
        handles, labels = legend['handles'], legend['labels']
        lgd = fig.legend(handles, labels, bbox_to_anchor=legend['loc'],
                loc='upper left', ncol=1, fontsize=11, frameon=False)
    
    ax.xaxis.set_minor_locator(MultipleLocator(24))
    ax.xaxis.set_major_locator(MultipleLocator(48))
    ax.xaxis.set_major_formatter('{x:.0f}')

    for ax in axes:
        ax.get_legend().remove()
        
    pad = 8
    ax = axes[0]
    annot = ax.annotate(dataset_name, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0),
                    xycoords=ax.yaxis.label, textcoords='offset points',
                    size='large', ha='right', va='center', rotation=90, fontsize=14)
    ax.annotate('Test on:', xy=(-0.05, 0.492), xycoords=ax.title, textcoords='offset points',
                size='large', ha='right', va='center', rotation=0, fontsize=13)

    plt.subplots_adjust(top=0.80, wspace=0.1)
    if legend is not None:
        plt.savefig('../figs/' + savename + '.png', format='png', dpi=600,
                bbox_extra_artists=(annot,lgd,), bbox_inches='tight', pad_inches=0)
    else:
        plt.savefig('../figs/' + savename + '.png', format='png', dpi=600,
                bbox_inches='tight', pad_inches=0)
    plt.show()
//  [python]
def metric_lineplot(df, predictors, metric, predictor_names, dataset_name,
    max_n_mut, savename='figure', legend=None, mutcounts=None, **kwargs):
    fig, axes = plt.subplots(1, max_n_mut+1,
                             figsize=((max_n_mut+1)*3, 4),
                             sharex=True, sharey=True)
    ax = axes[0]
    nmut_to_title = {
        1: 'Single mutants',
        2: 'Double mutants',
        3: 'Triple mutants',
        4: 'Quadruple mutants',
    }
    nmut_to_title.update({i: f'{i}th-order Mutants' for i in range(5, 11)})
    tmp = retrieve_metric(df, metric, n_mut=None, predictor=predictors)
    sns.lineplot(data=tmp, x='n_train', y='val',
                 hue='predictor', style='predictor', ax=ax,
                 hue_order=predictors, style_order=predictors, **kwargs)
    #ax.hlines(df[df.predictor == 'mutation'].mean().spearman, 48, 240, color='dimgrey')
    ax.set_title(f'mutants of all orders')
    ax.set_ylabel(metric_display_name[metric])
    ax.set_xlabel('Training data size')
    for n_mut in range(1, max_n_mut+1):
        ax = axes[n_mut]
        tmp = retrieve_metric(df, metric, n_mut=n_mut, predictor=predictors)
        sns.lineplot(data=tmp, x='n_train', y='val',
                     hue='predictor', style='predictor', ax=ax,
                     hue_order=predictors, style_order=predictors, **kwargs)
        ax.set_title(nmut_to_title[n_mut])
        ax.set_ylabel(metric_display_name[metric])
        ax.set_xlabel('Training data size')
    if mutcounts is not None:
        for i in range(max_n_mut+1):
            axes[i].annotate(f'Data size: {int(mutcounts[i])}',
                xy=(0.29, 0.03), xycoords='axes fraction', 
                fontsize=9)

    if legend is not None:
        handles, labels = legend['handles'], legend['labels']
        lgd = fig.legend(handles, labels, bbox_to_anchor=legend['loc'],
                loc='upper left', ncol=1, fontsize=11, frameon=False)
    
    ax.xaxis.set_minor_locator(MultipleLocator(24))
    ax.xaxis.set_major_locator(MultipleLocator(48))
    ax.xaxis.set_major_formatter('{x:.0f}')

    for ax in axes:
        ax.get_legend().remove()
        
    pad = 8
    ax = axes[0]
    annot = ax.annotate(dataset_name, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0),
                    xycoords=ax.yaxis.label, textcoords='offset points',
                    size='large', ha='right', va='center', rotation=90, fontsize=14)
    ax.annotate('Test on:', xy=(-0.05, 0.492), xycoords=ax.title, textcoords='offset points',
                size='large', ha='right', va='center', rotation=0, fontsize=13)

    plt.subplots_adjust(top=0.80, wspace=0.1)
    if legend is not None:
        plt.savefig('../figs/' + savename + '.png', format='png', dpi=600,
                bbox_extra_artists=(annot,lgd,), bbox_inches='tight', pad_inches=0)
    else:
        plt.savefig('../figs/' + savename + '.png', format='png', dpi=600,
                bbox_inches='tight', pad_inches=0)
    plt.show()
//  [python]
def plot_results(df_fashion, df_digit,df_oracle):
    fig, axis = plt.subplots(nrows=2, ncols=3, figsize=(14,6), constrained_layout=True)
    # fig.tight_layout()
    axis[0, 0] = sns.pointplot(data=df_fashion[["accuracy","val_accuracy"]], ax = axis[0,0], linewidth=2.5)
    axis[0, 0].set(xlabel='Epochs')
    axis[0, 0].set_ylabel('Accuracy', weight='bold')
    axis[0, 0].set_title("Fashion-MNIST")

    axis[1, 0] = sns.pointplot(data=df_fashion[["loss","val_loss"]], ax = axis[1,0], linewidth=2.5)
    axis[1, 0].set_ylabel('Loss', weight='bold')
    axis[1, 0].set(xlabel='Epochs')

    # axis[1, 0].set_title("Fashion-MNIST")

    axis[0, 1] = sns.pointplot(data=df_digit[["accuracy","val_accuracy"]],ax = axis[0,1], linewidth=2.5)
    axis[0, 1].set_title("MNIST-Digit")
    axis[0, 1].set_xlabel('Epochs')

    axis[1, 1] = sns.pointplot(data=df_digit[["loss","val_loss"]], ax = axis[1,1], linewidth=2.5)
    # axis[1, 1].set_title("MNIST-Digit")
    axis[1, 1].set(xlabel='Epochs')

    axis[0, 2] = sns.pointplot(data=df_oracle[["accuracy","val_accuracy"]],ax = axis[0,2], linewidth=2.5)
    axis[0, 2].set_title("Oracle-MNIST")
    axis[0, 2].set(xlabel='Epochs')

    axis[1, 2] = sns.pointplot(data=df_oracle[["loss","val_loss"]], ax = axis[1,2], linewidth=2.5)
    # axis[1, 2].set_title("Oracle-MNIST")
    axis[1, 2].set(xlabel='Epochs')

    fig.text(0.19,-0.07,'(a)')
    fig.text(0.52,-0.07,'(b)')
    fig.text(0.84,-0.07,'(c)')


    plt.show()
    fig.savefig('../chart/result.pdf',bbox_inches="tight")
//  [python]
def plot_results(df_fashion, df_digit,df_oracle):
    fig, axis = plt.subplots(nrows=2, ncols=3, figsize=(14,6), constrained_layout=True)
    # fig.tight_layout()
    axis[0, 0] = sns.lineplot(data=df_fashion[["accuracy","val_accuracy"]], ax = axis[0,0], linewidth=2.5)
    axis[0, 0].set(xlabel='Epochs')
    axis[0, 0].set_ylabel('Accuracy', weight='bold')
    axis[0, 0].set_title("Fashion-MNIST")

    axis[1, 0] = sns.lineplot(data=df_fashion[["loss","val_loss"]], ax = axis[1,0], linewidth=2.5)
    axis[1, 0].set_ylabel('Loss', weight='bold')
    axis[1, 0].set(xlabel='Epochs')

    # axis[1, 0].set_title("Fashion-MNIST")

    axis[0, 1] = sns.lineplot(data=df_digit[["accuracy","val_accuracy"]],ax = axis[0,1], linewidth=2.5)
    axis[0, 1].set_title("MNIST-Digit")
    axis[0, 1].set_xlabel('Epochs')

    axis[1, 1] = sns.lineplot(data=df_digit[["loss","val_loss"]], ax = axis[1,1], linewidth=2.5)
    # axis[1, 1].set_title("MNIST-Digit")
    axis[1, 1].set(xlabel='Epochs')

    axis[0, 2] = sns.lineplot(data=df_oracle[["accuracy","val_accuracy"]],ax = axis[0,2], linewidth=2.5)
    axis[0, 2].set_title("Oracle-MNIST")
    axis[0, 2].set(xlabel='Epochs')

    axis[1, 2] = sns.lineplot(data=df_oracle[["loss","val_loss"]], ax = axis[1,2], linewidth=2.5)
    # axis[1, 2].set_title("Oracle-MNIST")
    axis[1, 2].set(xlabel='Epochs')

    fig.text(0.19,-0.07,'(a)')
    fig.text(0.52,-0.07,'(b)')
    fig.text(0.84,-0.07,'(c)')


    plt.show()
    fig.savefig('../chart/result.pdf',bbox_inches="tight")
//  [python]
def _make_per_round_plot(df: pd.DataFrame, palette: dict, opponent: str, outpath: Path) -> None:
    # Sort columns based on their score at round 9
    sorted_columns = df.loc[9].sort_values(ascending=False).index

    plt.figure(figsize=(12, 6))
    ax = plt.gca()
    for col in sorted_columns:
        color = palette[col]
        plt.plot(df.index, df[col], label=col, color=color, linestyle="-")

    ax.set_ylim(0, 1)
    ax.set(xlabel="round number", ylabel="% of rounds won")
    ax.set(title=f"Per-round win ratio against {opponent}")
    ax.legend(loc="lower right")
    plt.tight_layout()
    plt.savefig(outpath)
    plt.show()
//  [python]
def _make_per_round_plot(df: pd.DataFrame, palette: dict, opponent: str, outpath: Path) -> None:
    # Sort columns based on their score at round 9
    sorted_columns = df.loc[9].sort_values(ascending=False).index

    plt.figure(figsize=(12, 6))
    ax = plt.gca()
    for col in sorted_columns:
        color = palette[col]
        sns.lineplot(x=df.index, y=df[col], ax=ax, label=col, color=color, linestyle="-")

    ax.set_ylim(0, 1)
    ax.set(xlabel="round number", ylabel="% of rounds won")
    ax.set(title=f"Per-round win ratio against {opponent}")
    ax.legend(loc="lower right")
    plt.tight_layout()
    plt.savefig(outpath)
    plt.show()
//  [python]
ax = analytical.plot(x='time', y='analytical', c='black', marker='o')
sns.set_style("ticks")
plicRDF = sol[sol['interfaceType'] == 'plicRDF']
plicRDF.to_csv("sinwaveTri.csv", index=False)


sns.pointplot(x='time', y='max', hue='Method', style="nCells", data=plicRDF,
             hue_order=['gradAlpha', 'fitParaboloid', 'RDF'], ax=ax).set(ylim=(0, 3.5))
//  [python]
ax = analytical.plot(x='time', y='analytical', c='black', marker='o')
sns.set_style("ticks")
plicRDF = sol[sol['interfaceType'] == 'plicRDF']
plicRDF.to_csv("sinwaveTri.csv", index=False)


sns.lineplot(x='time', y='max', hue='Method', style="nCells", data=plicRDF,
             hue_order=['gradAlpha', 'fitParaboloid', 'RDF'], ax=ax).set(ylim=(0, 3.5))
//  [python]
def plot_batch(batch_series, iters, saved_file, axis=None):
    '''
    :param batch_series: a batch of sequence
    :param iters: current iteration
    :return: plots up to six sequences on shared axis
    '''
    flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
    batch_size = np.shape(batch_series)[0]
    num_seq = np.minimum(len(flatui), batch_size)

    for i in range(0, num_seq):
        data = [_ for _ in enumerate(batch_series[i])]
        plt.plot([el[0] for el in data],
                     [el[1] for el in data],
                     color=flatui[i % len(flatui)],
                     ax=axis)
    str = "Sample plot after {} iterations".format(iters)
    plt.title(str)
    plt.savefig("./trained/{}/images/{}.png".format(saved_file, str))
    plt.close()
//  [python]
def plot_batch(batch_series, iters, saved_file, axis=None):
    '''
    :param batch_series: a batch of sequence
    :param iters: current iteration
    :return: plots up to six sequences on shared axis
    '''
    flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
    batch_size = np.shape(batch_series)[0]
    num_seq = np.minimum(len(flatui), batch_size)

    for i in range(0, num_seq):
        data = [_ for _ in enumerate(batch_series[i])]
        sns.lineplot(x=[el[0] for el in data],
                     y=[el[1] for el in data],
                     color=flatui[i % len(flatui)],
                     ax=axis)
    str = "Sample plot after {} iterations".format(iters)
    plt.title(str)
    plt.savefig("./trained/{}/images/{}.png".format(saved_file, str))
    plt.close()
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
    if smooth > 1:
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            datum[value] = smoothed_x

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

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

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

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

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

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

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

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

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

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

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

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

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

    plt.tight_layout(pad=0.5)
//  [python]
def generate_md_report(path_dir: Path, user):
    habit_table, productivity_table, corr = correlation(user)
    plt.figure(figsize=(6, 3))
    plt.xticks(rotation=20)
    fig = sns.tsplot(data=productivity_table, time='date', value='brain-activity')
    plot_path = str(path_dir / 'plot.png')
    plt.tight_layout()
    fig.figure.savefig(plot_path)

    with open(path_dir / "output.md", 'w') as file:
        file.write(f'# Weekly report, generated in {datetime.now().date()}\n')
        file.write("### Weekly habit statistics\n")
        file.write(habit_table.to_markdown() + "\n")
        file.write("### Weekly brain activity plot\n")
        file.write(f"![plot]({plot_path})\n")
        file.write("### Weekly correlation analysis of habits\n")
        file.write(corr.to_markdown() + "\n")
//  [python]
def generate_md_report(path_dir: Path, user):
    habit_table, productivity_table, corr = correlation(user)
    plt.figure(figsize=(6, 3))
    plt.xticks(rotation=20)
    fig = sns.lineplot(data=productivity_table, x='date', y='brain-activity')
    plot_path = str(path_dir / 'plot.png')
    plt.tight_layout()
    fig.figure.savefig(plot_path)

    with open(path_dir / "output.md", 'w') as file:
        file.write(f'# Weekly report, generated in {datetime.now().date()}\n')
        file.write("### Weekly habit statistics\n")
        file.write(habit_table.to_markdown() + "\n")
        file.write("### Weekly brain activity plot\n")
        file.write(f"![plot]({plot_path})\n")
        file.write("### Weekly correlation analysis of habits\n")
        file.write(corr.to_markdown() + "\n")
//  [python]
def sns_plot(chart_type: str, df):
    """ return seaborn plots """

    fig, ax = plt.subplots()
    if chart_type == "Scatter":
        with st.echo():
            sns.scatterplot(
                data=df,
                x="bill_depth_mm",
                y="bill_length_mm",
                hue="species",
            )
            plt.title("Bill Depth by Bill Length")
    elif chart_type == "Histogram":
        with st.echo():
            sns.histplot(data=df, x="bill_depth_mm")
            plt.title("Count of Bill Depth Observations")
    elif chart_type == "Bar":
        with st.echo():
            sns.barplot(data=df, x="species", y="bill_depth_mm")
            plt.title("Mean Bill Depth by Species")
    elif chart_type == "Boxplot":
        with st.echo():
            sns.boxplot(data=df)
            plt.title("Bill Depth Observations")
    elif chart_type == "Line":
        with st.echo():
            sns.pointplot(data=df, x=df.index, y="bill_length_mm")
            plt.title("Bill Length Over Time")
    elif chart_type == "3D Scatter":
        st.write("Seaborn doesn't do 3D ☹️. Here's 2D.")
        sns.scatterplot(data=df, x="bill_depth_mm", y="bill_length_mm", hue="island")
        plt.title("Just a 2D Scatterplot")
    return fig
//  [python]
def sns_plot(chart_type: str, df):
    """ return seaborn plots """

    fig, ax = plt.subplots()
    if chart_type == "Scatter":
        with st.echo():
            sns.scatterplot(
                data=df,
                x="bill_depth_mm",
                y="bill_length_mm",
                hue="species",
            )
            plt.title("Bill Depth by Bill Length")
    elif chart_type == "Histogram":
        with st.echo():
            sns.histplot(data=df, x="bill_depth_mm")
            plt.title("Count of Bill Depth Observations")
    elif chart_type == "Bar":
        with st.echo():
            sns.barplot(data=df, x="species", y="bill_depth_mm")
            plt.title("Mean Bill Depth by Species")
    elif chart_type == "Boxplot":
        with st.echo():
            sns.boxplot(data=df)
            plt.title("Bill Depth Observations")
    elif chart_type == "Line":
        with st.echo():
            sns.lineplot(data=df, x=df.index, y="bill_length_mm")
            plt.title("Bill Length Over Time")
    elif chart_type == "3D Scatter":
        st.write("Seaborn doesn't do 3D ☹️. Here's 2D.")
        sns.scatterplot(data=df, x="bill_depth_mm", y="bill_length_mm", hue="island")
        plt.title("Just a 2D Scatterplot")
    return fig
//  [python]
nfolds = 6

folds = [f"fold{i}" for i in range(1, nfolds + 1)]

for variable in ["loss", "rmse"]:
    plt.figure()

    df_test = pd.read_csv(
        f"results/test-{variable}.csv",
        header=None,
        names=["epoch"] + folds,
    )
    df_test["mode"] = "test"

    df_train = pd.read_csv(
        f"results/train-{variable}.csv",
        header=None,
        names=["epoch"] + folds,
    )
    df_train["mode"] = "train"

    df = pd.concat((df_test, df_train))

    df = df.melt(
        id_vars=["epoch", "mode"],
        value_vars=folds,
        var_name="fold",
        value_name=variable,
    )

    sns.pointplot(
        data=df,
        x="epoch",
        y=variable,
        hue="mode",
        markers=["o", "x"],
        linestyles=["-", "--"],
    )
    plt.savefig(f"results/{variable}.png")
//  [python]
nfolds = 6

folds = [f"fold{i}" for i in range(1, nfolds + 1)]

for variable in ["loss", "rmse"]:
    plt.figure()

    df_test = pd.read_csv(
        f"results/test-{variable}.csv",
        header=None,
        names=["epoch"] + folds,
    )
    df_test["mode"] = "test"

    df_train = pd.read_csv(
        f"results/train-{variable}.csv",
        header=None,
        names=["epoch"] + folds,
    )
    df_train["mode"] = "train"

    df = pd.concat((df_test, df_train))

    df = df.melt(
        id_vars=["epoch", "mode"],
        value_vars=folds,
        var_name="fold",
        value_name=variable,
    )

    sns.lineplot(
        data=df,
        x="epoch",
        y=variable,
        hue="mode",
        style="mode",
        markers=True,
        dashes=False,
    )
    plt.savefig(f"results/{variable}.png")
//  [python]
sns.set(style='darkgrid')   #Adds a grid
sns.pointplot(x='Image', y='Manual', data=df, hue='Unnamed: 0')
//  [python]
sns.set(style='darkgrid')   #Adds a grid
sns.lineplot(x='Image', y='Manual', data=df, hue='Unnamed: 0')
//  [python]
def plot_throughput_bler_timeline(self, df):
        sns.tsplot(df["time"], df["bler"])
//  [python]
def plot_throughput_bler_timeline(self, df):
        sns.lineplot(df["time"], df["bler"])
//  [python]
def plot_tail_for_one_model(alpha, accuracy, model_name='default'):
    data = {'Tail size': alpha, model_name: accuracy}
    df = pd.DataFrame(data, dtype=float)
    df = pd.melt(df, ['Tail size'], var_name="Models", value_name="Accuracy")
    ax = sns.tsplot(x="Tail size", y="Accuracy", unit="Models", condition="Models", data=df, ci=None)
    plt.xscale('log')
    plt.ylim(0, 100)
    save_dir = 'figures'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    plt.savefig('figures/tail_plot_%s.pdf' % model_name)
    plt.close()
//  [python]
def plot_tail_for_one_model(alpha, accuracy, model_name='default'):
    data = {'Tail size': alpha, model_name: accuracy}
    df = pd.DataFrame(data, dtype=float)
    df = pd.melt(df, ['Tail size'], var_name="Models", value_name="Accuracy")
    ax = sns.lineplot(x="Tail size", y="Accuracy", hue="Models", style="Models", data=df, markers=False, ci=None)
    plt.xscale('log')
    plt.ylim(0, 100)
    save_dir = 'figures'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    plt.savefig('figures/tail_plot_%s.pdf' % model_name)
    plt.close()
//  [python]
def plot_paired_ttests_pvalues(df):
    df_ttest = _get_ttest_df(df)
    all_sub_ttest_df = {
        n: _get_ttest_df(df, n_samples=n, random_state=123, sorted_idx=list(df_ttest.index))
        for n in range(50, len(df["instruction"].unique()), 50)
    }

    df_describe = pd.DataFrame(
        {
            "mean": {k: v.mean(axis=None) for k, v in all_sub_ttest_df.items()},
            "90% quantile": {k: v.stack().quantile(q=0.9) for k, v in all_sub_ttest_df.items()},
            "max": {k: v.max(axis=None) for k, v in all_sub_ttest_df.items()},
        }
    )

    melted = df_describe.melt(ignore_index=False, value_name="p-value", var_name="aggregator").reset_index(
        names="# samples"
    )

    with plot_config(rc={"lines.linewidth": 4, "axes.grid": False}):
        ax = sns.pointplot(melted, x="# samples", y="p-value", hue="aggregator")

        ax.axhline(y=0.05, color="black", linestyle="--", linewidth=2, alpha=0.5)

        # Get the handles and labels from the existing line plot legend
        handles, labels = ax.get_legend_handles_labels()

        # Create a new legend element for the horizontal line
        legend_elements = [Line2D([0], [0], color="black", linestyle="--", label="0.05")]

        # Combine the handles, labels, and new legend element
        all_handles = handles + legend_elements
        all_labels = labels + ["0.05"]

        # Plot the combined legend
        ax.legend(handles=all_handles, labels=all_labels)
    plt.show()
    return ax
//  [python]
def plot_paired_ttests_pvalues(df):
    df_ttest = _get_ttest_df(df)
    all_sub_ttest_df = {
        n: _get_ttest_df(df, n_samples=n, random_state=123, sorted_idx=list(df_ttest.index))
        for n in range(50, len(df["instruction"].unique()), 50)
    }

    df_describe = pd.DataFrame(
        {
            "mean": {k: v.mean(axis=None) for k, v in all_sub_ttest_df.items()},
            "90% quantile": {k: v.stack().quantile(q=0.9) for k, v in all_sub_ttest_df.items()},
            "max": {k: v.max(axis=None) for k, v in all_sub_ttest_df.items()},
        }
    )

    melted = df_describe.melt(ignore_index=False, value_name="p-value", var_name="aggregator").reset_index(
        names="# samples"
    )

    with plot_config(rc={"lines.linewidth": 4, "axes.grid": False}):
        ax = sns.lineplot(melted, x="# samples", y="p-value", hue="aggregator")

        ax.axhline(y=0.05, color="black", linestyle="--", linewidth=2, alpha=0.5)

        # Get the handles and labels from the existing line plot legend
        handles, labels = ax.get_legend_handles_labels()

        # Create a new legend element for the horizontal line
        legend_elements = [Line2D([0], [0], color="black", linestyle="--", label="0.05")]

        # Combine the handles, labels, and new legend element
        all_handles = handles + legend_elements
        all_labels = labels + ["0.05"]

        # Plot the combined legend
        ax.legend(handles=all_handles, labels=all_labels)
    plt.show()
    return ax
//  [python]
def vis_training_curves(history=None, output_dir: str = None) -> None: # OK
    """
    Visualizes the training curves of the model.

    Args:
        history: The history object returned by the model.fit() method.
        output_dir (Optional[str]): The output directory to save the training curves plot.

    Returns:
        None
    """
    # Extract the accuracy and loss values for training and validation data
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    epochs_range = range(len(acc))

    # Create dataframes for the training and validation data
    df_val = pd.DataFrame(
        {'run': 'validation', 'step': epochs_range, 'epoch_accuracy': val_acc, 'epoch_loss': val_loss})
    df_train = pd.DataFrame({'run': 'train', 'step': epochs_range, 'epoch_accuracy': acc, 'epoch_loss': loss})

    # Concatenate the dataframes
    frames = [df_val, df_train]
    df = pd.concat(frames)
    df = df.reset_index()

    # Plot the training curves
    plt.figure(figsize=(16, 6))
    plt.suptitle('Training curves', fontsize=16)
    plt.subplot(1, 2, 1)
    sns.pointplot(data=df, x="step", y="epoch_accuracy", hue="run").set_title("accuracy")
    plt.grid()
    plt.subplot(1, 2, 2)
    sns.pointplot(data=df, x="step", y="epoch_loss", hue="run").set_title("loss")
    plt.grid()
    plt.savefig(os.path.join(output_dir, 'Training_curves.png'))
//  [python]
def vis_training_curves(history=None, output_dir: str = None) -> None: # OK
    """
    Visualizes the training curves of the model.

    Args:
        history: The history object returned by the model.fit() method.
        output_dir (Optional[str]): The output directory to save the training curves plot.

    Returns:
        None
    """
    # Extract the accuracy and loss values for training and validation data
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    epochs_range = range(len(acc))

    # Create dataframes for the training and validation data
    df_val = pd.DataFrame(
        {'run': 'validation', 'step': epochs_range, 'epoch_accuracy': val_acc, 'epoch_loss': val_loss})
    df_train = pd.DataFrame({'run': 'train', 'step': epochs_range, 'epoch_accuracy': acc, 'epoch_loss': loss})

    # Concatenate the dataframes
    frames = [df_val, df_train]
    df = pd.concat(frames)
    df = df.reset_index()

    # Plot the training curves
    plt.figure(figsize=(16, 6))
    plt.suptitle('Training curves', fontsize=16)
    plt.subplot(1, 2, 1)
    sns.lineplot(data=df, x="step", y="epoch_accuracy", hue="run").set_title("accuracy")
    plt.grid()
    plt.subplot(1, 2, 2)
    sns.lineplot(data=df, x="step", y="epoch_loss", hue="run").set_title("loss")
    plt.grid()
    plt.savefig(os.path.join(output_dir, 'Training_curves.png'))
//  [python]
def plot_time_ticks(self, time_ticks_list, name):
        # time_ticks vs sample
        plt.figure()
        x = np.linspace(0, len(time_ticks_list) - 1, len(time_ticks_list))
        plt.plot(x, time_ticks_list)
        plt.xlabel("Samples")
        plt.ylabel("Second")
        plt.tight_layout()
        # plt.show()
        plt.savefig(self.figure_dir + "timeticks/" + name, dpi=300)
        plt.close()
//  [python]
def plot_time_ticks(self, time_ticks_list, name):
        # time_ticks vs sample
        plt.figure()
        x = np.linspace(0, len(time_ticks_list) - 1, len(time_ticks_list))
        sns.lineplot(x=x, y=time_ticks_list)
        plt.xlabel("Samples")
        plt.ylabel("Second")
        plt.tight_layout()
        # plt.show()
        plt.savefig(self.figure_dir + "timeticks/" + name, dpi=300)
        plt.close()
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, legend=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="darkgrid", font_scale=2.0)
    sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd', legend=legend, **kwargs)
    #sns.lineplot(data=data, x=xaxis, y=value, ci='sd', hue=condition, style=condition, dashes=False, markers=["p","h","v","s","o","D","X","P","*"], ms=8, markevery=20, markeredgewidth=0.0, legend=legend, **kwargs)
    #plt.plot(data[xaxis],data[value])
    """
    If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
    tsplot to lineplot replacing L29 with:

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

    Changes the colorscheme and the default legend style, though.
    """
    #plt.legend(loc='best')
    #plt.legend(loc='upper center', bbox_to_anchor=(1.2,0.8), prop={'size':20})

    """
    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})
    #print(np.isnan(data[value]).any())
    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='both', scilimits=(0,0))

    plt.tight_layout(pad=0.5)
    plt.legend(loc='upper left')
    plt.show()
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, legend=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="darkgrid", font_scale=2.0)
    #sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd', legend=legend, **kwargs)
    sns.lineplot(data=data, x=xaxis, y=value, ci='sd', hue=condition, style=condition, dashes=False, markers=["p","h","v","s","o","D","X","P","*"], ms=8, markevery=20, markeredgewidth=0.0, legend=legend, **kwargs)
    #plt.plot(data[xaxis],data[value])
    """
    If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
    tsplot to lineplot replacing L29 with:

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

    Changes the colorscheme and the default legend style, though.
    """
    #plt.legend(loc='best')
    #plt.legend(loc='upper center', bbox_to_anchor=(1.2,0.8), prop={'size':20})

    """
    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})
    #print(np.isnan(data[value]).any())
    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='both', scilimits=(0,0))

    plt.tight_layout(pad=0.5)
    plt.legend(loc='upper left')
    plt.show()
//  [python]
def learning_curve(log_dir, window=10):
    # Read data
    training_data = pd.read_csv(log_dir + 'training_data.csv', index_col=None)

    # Calculate episode rewards
    episode_rewards = calc_episode_rewards(training_data)

    # Calculate rolling window metrics
    rolling_average = episode_rewards.rolling(window=window, min_periods=window).mean().dropna()
    rolling_max = episode_rewards.rolling(window=window, min_periods=window).max().dropna()
    rolling_min = episode_rewards.rolling(window=window, min_periods=window).min().dropna()

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

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

    # Save figure
    plt.savefig(log_dir + 'learning_curve.png')
//  [python]
def learning_curve(log_dir, window=10):
    # Read data
    training_data = pd.read_csv(log_dir + 'training_data.csv', index_col=None)

    # Calculate episode rewards
    episode_rewards = calc_episode_rewards(training_data)

    # Calculate rolling window metrics
    rolling_average = episode_rewards.rolling(window=window, min_periods=window).mean().dropna()
    rolling_max = episode_rewards.rolling(window=window, min_periods=window).max().dropna()
    rolling_min = episode_rewards.rolling(window=window, min_periods=window).min().dropna()

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

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

    # Save figure
    plt.savefig(log_dir + 'learning_curve.png')
//  [python]
def _plot_join_q_plot(
        df_label_tuples,
        num_bins,
        folder,
        name,
        ax_lim=(0, 1),
        y_label="Utility (Solve Rate)",
        x_label="Percentile",
):
    c = cycle(["r", "GoldenRod", "forestgreen", "yellow"])

    fig = plt.figure(figsize=(5.2, 5))
    ax = fig.gca()

    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)

    for df, label in df_label_tuples:
        df['bin_id'] = pd.qcut(df.score, num_bins, precision=3, labels=False)
        df['bin_labels'] = pd.qcut(df.score, num_bins, precision=3)

        sns.pointplot(data=df,
                     x='bin_id',
                     y='utility',
                     color=next(c),
                     linestyle="-",
                     linewidth=2,
                     join=True,
                     ci=95,
                     ax=ax, alpha=1, label=label)

        print(f"{label} range per bin")
        print(df[['bin_id', 'bin_labels']].value_counts(ascending=True).reset_index(name='count'))

    positions = np.arange(num_bins)
    labels = ((positions + 1) * 100 / num_bins).astype(int)
    ax.xaxis.set_major_locator(mticker.FixedLocator(positions))
    ax.xaxis.set_major_formatter(mticker.FixedFormatter(labels))

    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_ylim(ax_lim)
    plt.legend(frameon=False)
    plt.tight_layout(rect=(-0.03, -0.03, 1.05, 1.03))

    log_plot_to_wandb(wandb_logger, f"Prompting/{name}", backend=plt, dpi=args.dpi)

    if not os.path.isdir(folder):
        os.makedirs(folder)
    path = os.path.join(folder, f"{name}")
    plt.savefig(f"{path}.pdf", bbox_inches="tight")

    plt.show()
//  [python]
def _plot_join_q_plot(
        df_label_tuples,
        num_bins,
        folder,
        name,
        ax_lim=(0, 1),
        y_label="Utility (Solve Rate)",
        x_label="Percentile",
):
    c = cycle(["r", "GoldenRod", "forestgreen", "yellow"])

    fig = plt.figure(figsize=(5.2, 5))
    ax = fig.gca()

    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)

    for df, label in df_label_tuples:
        df['bin_id'] = pd.qcut(df.score, num_bins, precision=3, labels=False)
        df['bin_labels'] = pd.qcut(df.score, num_bins, precision=3)

        sns.lineplot(data=df,
                     x='bin_id',
                     y='utility',
                     color=next(c),
                     linestyle="-",
                     linewidth=2,
                     err_style="bars", markers=True, dashes=False, ci=95,
                     err_kws={"fmt": 'o', "linewidth": 2, "capsize": 6},
                     ax=ax, alpha=1, label=label)

        print(f"{label} range per bin")
        print(df[['bin_id', 'bin_labels']].value_counts(ascending=True).reset_index(name='count'))

    positions = np.arange(num_bins)
    labels = ((positions + 1) * 100 / num_bins).astype(int)
    ax.xaxis.set_major_locator(mticker.FixedLocator(positions))
    ax.xaxis.set_major_formatter(mticker.FixedFormatter(labels))

    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_ylim(ax_lim)
    plt.legend(frameon=False)
    plt.tight_layout(rect=(-0.03, -0.03, 1.05, 1.03))

    log_plot_to_wandb(wandb_logger, f"Prompting/{name}", backend=plt, dpi=args.dpi)

    if not os.path.isdir(folder):
        os.makedirs(folder)
    path = os.path.join(folder, f"{name}")
    plt.savefig(f"{path}.pdf", bbox_inches="tight")

    plt.show()
//  [python]
def single_plot(df, ax, variable, lin_trend=False, legend=True):

    g = sns.tsplot(
        data=df,
        time="n-isolates",
        value=variable,
        condition="kbp-length",
        norm=LogNorm(),
        ci="sd",
        color="Blues_d",
        marker=".",
        markeredgecolor=None,
        ax=ax,
        legend=legend,
    )
    ax.set_xscale("log")
    ax.set_xlabel("n. isolates")
    ax.grid(alpha=0.2)

    # optionally plot a linear trend
    if lin_trend:
        plot_lin_trend(df, "n-isolates", variable, ax)

    if legend:
        g.legend(
            title="avg. isolate length (kbp)",
            fontsize="small",
            title_fontsize="medium",
            ncol=2,
        )
//  [python]
def single_plot(df, ax, variable, lin_trend=False, legend=True):

    g = sns.lineplot(
        data=df,
        x="n-isolates",
        y=variable,
        hue="kbp-length",
        hue_norm=LogNorm(),
        ci="sd",
        palette="Blues_d",
        marker=".",
        markeredgecolor=None,
        ax=ax,
        legend=legend,
    )
    ax.set_xscale("log")
    ax.set_xlabel("n. isolates")
    ax.grid(alpha=0.2)

    # optionally plot a linear trend
    if lin_trend:
        plot_lin_trend(df, "n-isolates", variable, ax)

    if legend:
        g.legend(
            title="avg. isolate length (kbp)",
            fontsize="small",
            title_fontsize="medium",
            ncol=2,
        )
//  [python]
def time_series_numerical_categorical(self):
        display(('--------------------bar plot of each numerical variables segmented by a categorical variables--------------------'))
        for a,b in [(m,n) for m in self.categorical_variables   for n in self.numerical_variables]:
           # if x != y:
            
            sns.pointplot(data=self.dataframe, x=self.date_variable, hue=a,  y=b)
           
            plt.title('Time series plot of '+ b + ' and ' + self.date_variable,size=16, y=1.05)
            plt.ylabel(b)
            plt.legend(loc="upper right", bbox_to_anchor=(1.2,1.0))
            plt.xlabel(self.date_variable)
            plt.xticks(rotation=90)
            plt.grid(True)
            plt.show()
//  [python]
def time_series_numerical_categorical(self):
        display(('--------------------bar plot of each numerical variables segmented by a categorical variables--------------------'))
        for a,b in [(m,n) for m in self.categorical_variables   for n in self.numerical_variables]:
           # if x != y:
            
            sns.lineplot(data=self.dataframe, x=self.date_variable, hue=a,  y=b)
           
            plt.title('Time series plot of '+ b + ' and ' + self.date_variable,size=16, y=1.05)
            plt.ylabel(b)
            plt.legend(loc="upper right", bbox_to_anchor=(1.2,1.0))
            plt.xlabel(self.date_variable)
            plt.xticks(rotation=90)
            plt.grid(True)
            plt.show()
//  [python]
def line_plot_multiple(self):
        display(('--------------------time series plot of each variable --------------------'))

        for x in self.categorical_variables:
                
                df_d=self.dataframe.groupby([timeseries,x], as_index=False)[value].agg({'group_size':'sum'})
                sns.tsplot(data=df_d, time=timeseries, condition=x,  value="group_size")
                plt.title('Time series plot of '+ x + ' and ' + timeseries,size=16, y=1.05)
                plt.ylabel(x)
                plt.legend(loc="upper right", bbox_to_anchor=(1.2,1.0))
                plt.xlabel(timeseries)
                plt.grid(True)
                plt.show()
//  [python]
def line_plot_multiple(self):
        display(('--------------------time series plot of each variable --------------------'))

        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.title('Time series plot of '+ x + ' and ' + timeseries,size=16, y=1.05)
                plt.ylabel(x)
                plt.legend(loc="upper right", bbox_to_anchor=(1.2,1.0))
                plt.xlabel(timeseries)
                plt.grid(True)
                plt.show()
//  [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.pointplot(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()