jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
results['Method'] = methods

plt.figure(figsize=[8,4])
sns.barplot(data=results, x='AUC', y='Method')
plt.xlim(0.2, 0.85)
sns.utils.despine()
//  [python]
def plot_data(pincp, privcov):
    plt.figure(figsize=(7.5,2.5))
    sns.set_theme(style="white", palette="pastel", font_scale=1.15, font='DejaVu Sans')
    bins = [20000,40000,60000,80000,100000]
    incomeranges = np.digitize(pincp, bins=bins)
    avgs = [privcov[incomeranges == i].mean() for i in range(len(bins)+1)]
    plt.bar(range(len(bins)+1),avgs)
    plt.gca().set_xticklabels(['', '<20K', '20K-40K','40K-60K','60K-80K','80K-100K', '>100K'])
    plt.ylabel('frac w/private insurance')
    plt.gca().set_ylim([0,1])
    plt.xlabel('household income ($)')
    sns.despine(top=True, right=True)
    plt.subplots_adjust(top=0.9, bottom=0.28)
    os.makedirs("./logistic-plots/", exist_ok=True)
    plt.savefig("./logistic-plots/raw_data.pdf")
//  [python]
def plot_data(pincp, privcov):
    plt.figure(figsize=(7.5,2.5))
    sns.set_theme(style="white", palette="pastel", font_scale=1.15, font='DejaVu Sans')
    bins = [20000,40000,60000,80000,100000]
    incomeranges = np.digitize(pincp, bins=bins)
    avgs = [privcov[incomeranges == i].mean() for i in range(len(bins)+1)]
    plt.bar(range(len(bins)+1),avgs)
    plt.gca().set_xticklabels(['', '<20K', '20K-40K','40K-60K','60K-80K','80K-100K', '>100K'])
    plt.ylabel('frac w/private insurance')
    plt.gca().set_ylim([0,1])
    plt.xlabel('household income ($)')
    sns.utils.despine(top=True, right=True)
    plt.subplots_adjust(top=0.9, bottom=0.28)
    os.makedirs("./logistic-plots/", exist_ok=True)
    plt.savefig("./logistic-plots/raw_data.pdf")
//  [python]
def despine_and_make_title(self, fig):
        sns.despine(fig=fig, left=True, bottom=True)
        fig.suptitle(f'{self._location.name} ({self._location.id})',
                     x=0.5,
                     fontsize=self.title_fontsize,
                     ha='center')
//  [python]
def despine_and_make_title(self, fig):
        sns.utils.despine(fig=fig, left=True, bottom=True)
        fig.suptitle(f'{self._location.name} ({self._location.id})',
                     x=0.5,
                     fontsize=self.title_fontsize,
                     ha='center')
//  [python]
def plot_feature_importance(model, features, model_alias):
    
    importance = model.feature_importances_
    feature_importance = list(zip(features, importance))

    feature_importance.sort(key = lambda x: x[1])

    # split sorted features_importance into x,y
    feat = [f[0] for f in feature_importance]
    imp = [i[1] for i in feature_importance]

    # Plot feature importance
    plt.figure(figsize=(7, 5), dpi=100)
    plt.title(f'Feature Importance: {model_alias}', fontsize=11)
    plt.barh(feat, imp, color='#3298dc')
    plt.xlabel('Feature Score', fontsize=9)
    sns.despine()
    plt.show();
//  [python]
def plot_feature_importance(model, features, model_alias):
    
    importance = model.feature_importances_
    feature_importance = list(zip(features, importance))

    feature_importance.sort(key = lambda x: x[1])

    # split sorted features_importance into x,y
    feat = [f[0] for f in feature_importance]
    imp = [i[1] for i in feature_importance]

    # Plot feature importance
    plt.figure(figsize=(7, 5), dpi=100)
    plt.title(f'Feature Importance: {model_alias}', fontsize=11)
    plt.barh(feat, imp, color='#3298dc')
    plt.xlabel('Feature Score', fontsize=9)
    sns.utils.despine()
    plt.show();
//  [python]
def plot_2d_pareto(trajectories: dict, scale):
    """Adaptation of code from: https://github.com/Cranial-XIX/CAGrad"""
    fig, ax = plt.subplots(figsize=(6, 5))

    F = Toy(scale=scale)

    losses = []
    for res in trajectories.values():
        losses.append(F.batch_forward(torch.from_numpy(res["traj"])))

    yy = -8.3552
    x = np.linspace(-7, 7, 100)

    inpt = np.stack((x, [yy] * len(x))).T
    Xs = torch.from_numpy(inpt).float()
    Ys = F.batch_forward(Xs)

    plt.plot(
        Ys.numpy()[:, 0],
        Ys.numpy()[:, 1],
        "-",
        linewidth=8,
        color="#72727A",
        label="Pareto Front",
    )  # Pareto front

    for i, tt in enumerate(losses):
        plt.scatter(
            tt[0, 0],
            tt[0, 1],
            color="k",
            s=150,
            zorder=10,
            label="Initial Point" if i == 0 else None,
        )
        colors = matplotlib.cm.magma_r(np.linspace(0.1, 0.6, tt.shape[0]))
        # colors = matplotlib.cm.plasma_r(np.linspace(0.1, 0.6, tt.shape[0]))
        plt.scatter(tt[:, 0], tt[:, 1], color=colors, s=5, zorder=9, rasterized=True)

    sns.despine()
    ax.set_xlabel(r"$\mathcal{L}_1$", size=30)
    ax.set_ylabel(r"$\mathcal{L}_2$", size=30)
    ax.xaxis.set_label_coords(1.015, -0.03)
    ax.yaxis.set_label_coords(-0.01, 1.01)

    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(20)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(20)

    opt_l0, opt_l1 = get_opt(scale)
    plt.scatter(opt_l0, opt_l1, marker='*', color="black", s=500, zorder=100)

    return ax, fig
//  [python]
def plot_2d_pareto(trajectories: dict, scale):
    """Adaptation of code from: https://github.com/Cranial-XIX/CAGrad"""
    fig, ax = plt.subplots(figsize=(6, 5))

    F = Toy(scale=scale)

    losses = []
    for res in trajectories.values():
        losses.append(F.batch_forward(torch.from_numpy(res["traj"])))

    yy = -8.3552
    x = np.linspace(-7, 7, 100)

    inpt = np.stack((x, [yy] * len(x))).T
    Xs = torch.from_numpy(inpt).float()
    Ys = F.batch_forward(Xs)

    plt.plot(
        Ys.numpy()[:, 0],
        Ys.numpy()[:, 1],
        "-",
        linewidth=8,
        color="#72727A",
        label="Pareto Front",
    )  # Pareto front

    for i, tt in enumerate(losses):
        plt.scatter(
            tt[0, 0],
            tt[0, 1],
            color="k",
            s=150,
            zorder=10,
            label="Initial Point" if i == 0 else None,
        )
        colors = matplotlib.cm.magma_r(np.linspace(0.1, 0.6, tt.shape[0]))
        # colors = matplotlib.cm.plasma_r(np.linspace(0.1, 0.6, tt.shape[0]))
        plt.scatter(tt[:, 0], tt[:, 1], color=colors, s=5, zorder=9, rasterized=True)

    sns.utils.despine()
    ax.set_xlabel(r"$\mathcal{L}_1$", size=30)
    ax.set_ylabel(r"$\mathcal{L}_2$", size=30)
    ax.xaxis.set_label_coords(1.015, -0.03)
    ax.yaxis.set_label_coords(-0.01, 1.01)

    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(20)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(20)

    opt_l0, opt_l1 = get_opt(scale)
    plt.scatter(opt_l0, opt_l1, marker='*', color="black", s=500, zorder=100)

    return ax, fig
//  [python]
def add_pca_inset(
    fig,
    pca,
    loc=[0.25, 0.15, 0.2, 0.2],
    ax=None,
):
    if ax is None:
        ax = fig.add_axes(loc)
    ax.plot(np.arange(len(pca.components_)), np.cumsum(pca.explained_variance_ratio_))
    ax.set_xlabel("# of PCs")
    ax.set_ylabel("VAF")
    ax.set_xticks([0, 3, 20])
    prep_plt(ax)
    sns.despine(ax=ax, right=False, top=False)
    return ax
//  [python]
def add_pca_inset(
    fig,
    pca,
    loc=[0.25, 0.15, 0.2, 0.2],
    ax=None,
):
    if ax is None:
        ax = fig.add_axes(loc)
    ax.plot(np.arange(len(pca.components_)), np.cumsum(pca.explained_variance_ratio_))
    ax.set_xlabel("# of PCs")
    ax.set_ylabel("VAF")
    ax.set_xticks([0, 3, 20])
    prep_plt(ax)
    sns.utils.despine(ax=ax, right=False, top=False)
    return ax
//  [python]
def plot_histograms(df_list,alpha,delta):
    sizes = torch.cat(df_list[0]['sizes'].tolist(),dim=0).numpy()
    d = np.diff(np.unique(sizes)).min()
    lofb = sizes.min() - float(d)/2
    rolb = sizes.max() + float(d)/2

    fdr_arrays = []
    sizes_arrays = []
    labels = []
    for i in range(len(df_list)):
        df = df_list[i]
        #fdrs = df['FDR'][df['FDR'] > alpha/2]
        fdrs = df['FDR']
        fdr_arrays = fdr_arrays + [np.array(fdrs.tolist()),]

        # Sizes will be 10 times as big as recall, since we pool it over runs.
        sizes = torch.cat(df['sizes'].tolist(),dim=0).numpy()
        sizes_arrays = sizes_arrays + [sizes,]
        labels = labels + [df['region name'][0],]

    # First plot: violins
    fig = plt.figure(figsize=(6,3))
    ax = fig.gca()
    sns.violinplot(data=fdr_arrays, ax=ax,orient='h',inner=None)
    ax.set_xlabel('FDR', fontsize=14)
    ax.locator_params(axis='x', nbins=4)
    ax.set_yticklabels(labels)
    ax.axvline(x=alpha,c='#999999',linestyle='--',alpha=0.7)
    ax.tick_params(axis='both', labelsize=14)
    sns.despine(ax=ax,top=True,right=True)
    plt.tight_layout()
    os.makedirs('../outputs',exist_ok=True)
    plt.savefig('../' + (f'outputs/violins_tables/{alpha}_{delta}_coco_violins').replace('.','_') + '.pdf')

    # Second plot: sizes table
    table_string = table_function(sizes_arrays,labels)
    os.makedirs('../outputs',exist_ok=True)
    table_file = open('../' + (f'outputs/violins_tables/{alpha}_{delta}_coco_table').replace('.','_') + '.txt', "w")
    n = table_file.write(table_string)
    table_file.close()
//  [python]
def plot_histograms(df_list,alpha,delta):
    sizes = torch.cat(df_list[0]['sizes'].tolist(),dim=0).numpy()
    d = np.diff(np.unique(sizes)).min()
    lofb = sizes.min() - float(d)/2
    rolb = sizes.max() + float(d)/2

    fdr_arrays = []
    sizes_arrays = []
    labels = []
    for i in range(len(df_list)):
        df = df_list[i]
        #fdrs = df['FDR'][df['FDR'] > alpha/2]
        fdrs = df['FDR']
        fdr_arrays = fdr_arrays + [np.array(fdrs.tolist()),]

        # Sizes will be 10 times as big as recall, since we pool it over runs.
        sizes = torch.cat(df['sizes'].tolist(),dim=0).numpy()
        sizes_arrays = sizes_arrays + [sizes,]
        labels = labels + [df['region name'][0],]

    # First plot: violins
    fig = plt.figure(figsize=(6,3))
    ax = fig.gca()
    sns.violinplot(data=fdr_arrays, ax=ax,orient='h',inner=None)
    ax.set_xlabel('FDR', fontsize=14)
    ax.locator_params(axis='x', nbins=4)
    ax.set_yticklabels(labels)
    ax.axvline(x=alpha,c='#999999',linestyle='--',alpha=0.7)
    ax.tick_params(axis='both', labelsize=14)
    sns.utils.despine(ax=ax,top=True,right=True)
    plt.tight_layout()
    os.makedirs('../outputs',exist_ok=True)
    plt.savefig('../' + (f'outputs/violins_tables/{alpha}_{delta}_coco_violins').replace('.','_') + '.pdf')

    # Second plot: sizes table
    table_string = table_function(sizes_arrays,labels)
    os.makedirs('../outputs',exist_ok=True)
    table_file = open('../' + (f'outputs/violins_tables/{alpha}_{delta}_coco_table').replace('.','_') + '.txt', "w")
    n = table_file.write(table_string)
    table_file.close()
//  [python]
def data_scatter(data, label_x, label_y, c, title, cmap=None):
    x = data[label_x]
    y = data[label_y]
    if cmap is None:
        plt.scatter(x, y, c=c, s=50, alpha=0.75, label='')
    else:
        z = data[c]
        plt.scatter(x, y, c=z, s=50, alpha=0.75, label='', cmap=cmap)

    xmin, xmax = np.min(x), np.max(x)
    # ideal fit
    mae, mae_std, rmse, r2, R2 = error_stats(x, y, verbose=False)

    info_str = '\n'.join(['ideal fit',
                          '$R^2=%.3f$' % R2,
                          '$r^2=%.3f$' % r2,
                          'MAE =%2.3f (%3.2f)' % (mae, mae_std),
                          'RMSE  =%2.3f' % rmse])
    plt.plot([xmin, xmax], [xmin, xmax], ls='--',
             c='k', alpha=0.5, lw=3, label=info_str)
    plt.xlabel(label_x)
    plt.ylabel(label_y)
    sns.despine()
    plt.title(title)
    plt.legend(loc='upper left')
    if cmap is not None:
        plt.colorbar()
    plt.show()
    return
//  [python]
def data_scatter(data, label_x, label_y, c, title, cmap=None):
    x = data[label_x]
    y = data[label_y]
    if cmap is None:
        plt.scatter(x, y, c=c, s=50, alpha=0.75, label='')
    else:
        z = data[c]
        plt.scatter(x, y, c=z, s=50, alpha=0.75, label='', cmap=cmap)

    xmin, xmax = np.min(x), np.max(x)
    # ideal fit
    mae, mae_std, rmse, r2, R2 = error_stats(x, y, verbose=False)

    info_str = '\n'.join(['ideal fit',
                          '$R^2=%.3f$' % R2,
                          '$r^2=%.3f$' % r2,
                          'MAE =%2.3f (%3.2f)' % (mae, mae_std),
                          'RMSE  =%2.3f' % rmse])
    plt.plot([xmin, xmax], [xmin, xmax], ls='--',
             c='k', alpha=0.5, lw=3, label=info_str)
    plt.xlabel(label_x)
    plt.ylabel(label_y)
    sns.utils.despine()
    plt.title(title)
    plt.legend(loc='upper left')
    if cmap is not None:
        plt.colorbar()
    plt.show()
    return
//  [python]
def simplified_paper_plot(df_pred_uci):
    cm = 1/2.54  # centimeters in inches
    sns.set()
    sns.set_style("white")
    sns.set_style("ticks")
    sns.despine()
    sns.set_context("paper")
    sns.color_palette("tab10")

    print ("Generating point plots") 
    print (df_pred_uci.head())
    dataset_names = df_pred_uci["Dataset"].unique()
    new_dataset_names = [label.replace('-', '-\n') for label in dataset_names]
    print (new_dataset_names, dataset_names)


    #================================================
    print (f"Generating Interval Score")
    df_pred_uci["lower"] = df_pred_uci["Mu"] - 2*df_pred_uci["Sigma"]
    df_pred_uci["lower"].mask(df_pred_uci["Method"]=="Laplace", df_pred_uci["Mu"] - 3*df_pred_uci["Sigma"], inplace=True)
    df_pred_uci["upper"] = df_pred_uci["Mu"] + 2*df_pred_uci["Sigma"]
    df_pred_uci["upper"].mask(df_pred_uci["Method"]=="Laplace", df_pred_uci["Mu"] + 3*df_pred_uci["Sigma"], inplace=True)
    
    df_pred_uci["Interval Score"] = df_pred_uci["upper"] - df_pred_uci["lower"] \
     + (2/0.95)*(df_pred_uci["lower"]-df_pred_uci["Target"])*(df_pred_uci["Target"]<df_pred_uci["lower"]) \
     + (2/0.95)*(df_pred_uci["Target"] - df_pred_uci["upper"])*(df_pred_uci["Target"]>df_pred_uci["upper"])
    
    fig = plt.figure(figsize=(14.2*cm, 14.2*cm/2.0))
    gs = fig.add_gridspec(2, 1)
    ax = fig.add_subplot(gs[0,0])
    #RMSE
    df_pred_uci["RMSE"] = (df_pred_uci["Mu"] - df_pred_uci["Target"])**2
    
    g = sns.pointplot(x="Dataset", y="RMSE", hue="Method", 
                      markers=["*","D","o", "x" ],
                      linestyles=["-","--","-.",":"],
                      dodge=0.45,
                      join=False, ci='sd',palette=["C2", "C3", "C0", "C1"],
                       data=df_pred_uci, legend=False)
    g.set_xticklabels([])
    g.get_legend().remove()
    # Improve the legend 
    handles, labels = g.get_legend_handles_labels()
    print (labels)
    fig.legend(handles, labels, bbox_to_anchor=(0.5, 0.85), loc='lower center', ncol=4, fancybox=True, shadow=True)

    ax = fig.add_subplot(gs[1,0])
    g = sns.pointplot(x="Dataset", y="Interval Score", hue="Method", 
                      markers=["*","D","o", "x" ],
                      linestyles=["-","--","-.",":"],
                      dodge=0.45,
                      join=False, ci='sd',palette=["C2", "C3", "C0", "C1"],
                       data=df_pred_uci, legend=False)
    g.set(yscale="log")
    g.get_legend().remove()
    g.set_xticklabels(new_dataset_names, fontsize='x-small')
    plt.savefig(os.path.join(output_dir, "RMSE_IS_Comb_point_uci.pdf"))
    plt.show()
//  [python]
def simplified_paper_plot(df_pred_uci):
    cm = 1/2.54  # centimeters in inches
    sns.set()
    sns.set_style("white")
    sns.set_style("ticks")
    sns.utils.despine()
    sns.set_context("paper")
    sns.color_palette("tab10")

    print ("Generating point plots") 
    print (df_pred_uci.head())
    dataset_names = df_pred_uci["Dataset"].unique()
    new_dataset_names = [label.replace('-', '-\n') for label in dataset_names]
    print (new_dataset_names, dataset_names)


    #================================================
    print (f"Generating Interval Score")
    df_pred_uci["lower"] = df_pred_uci["Mu"] - 2*df_pred_uci["Sigma"]
    df_pred_uci["lower"].mask(df_pred_uci["Method"]=="Laplace", df_pred_uci["Mu"] - 3*df_pred_uci["Sigma"], inplace=True)
    df_pred_uci["upper"] = df_pred_uci["Mu"] + 2*df_pred_uci["Sigma"]
    df_pred_uci["upper"].mask(df_pred_uci["Method"]=="Laplace", df_pred_uci["Mu"] + 3*df_pred_uci["Sigma"], inplace=True)
    
    df_pred_uci["Interval Score"] = df_pred_uci["upper"] - df_pred_uci["lower"] \
     + (2/0.95)*(df_pred_uci["lower"]-df_pred_uci["Target"])*(df_pred_uci["Target"]<df_pred_uci["lower"]) \
     + (2/0.95)*(df_pred_uci["Target"] - df_pred_uci["upper"])*(df_pred_uci["Target"]>df_pred_uci["upper"])
    
    fig = plt.figure(figsize=(14.2*cm, 14.2*cm/2.0))
    gs = fig.add_gridspec(2, 1)
    ax = fig.add_subplot(gs[0,0])
    #RMSE
    df_pred_uci["RMSE"] = (df_pred_uci["Mu"] - df_pred_uci["Target"])**2
    
    g = sns.pointplot(x="Dataset", y="RMSE", hue="Method", 
                      markers=["*","D","o", "x" ],
                      linestyles=["-","--","-.",":"],
                      dodge=0.45,
                      join=False, ci='sd',palette=["C2", "C3", "C0", "C1"],
                       data=df_pred_uci, legend=False)
    g.set_xticklabels([])
    g.get_legend().remove()
    # Improve the legend 
    handles, labels = g.get_legend_handles_labels()
    print (labels)
    fig.legend(handles, labels, bbox_to_anchor=(0.5, 0.85), loc='lower center', ncol=4, fancybox=True, shadow=True)

    ax = fig.add_subplot(gs[1,0])
    g = sns.pointplot(x="Dataset", y="Interval Score", hue="Method", 
                      markers=["*","D","o", "x" ],
                      linestyles=["-","--","-.",":"],
                      dodge=0.45,
                      join=False, ci='sd',palette=["C2", "C3", "C0", "C1"],
                       data=df_pred_uci, legend=False)
    g.set(yscale="log")
    g.get_legend().remove()
    g.set_xticklabels(new_dataset_names, fontsize='x-small')
    plt.savefig(os.path.join(output_dir, "RMSE_IS_Comb_point_uci.pdf"))
    plt.show()
//  [python]
def jitter_stripplot(df, x="mean_stopped_cost_and_penalty"):
    # https://seaborn.pydata.org/examples/jitter_stripplot.html#jitter-stripplot
    f, ax = plt.subplots()
    sns.despine(bottom=True, left=True)
    sns.stripplot(x=x, y="control_type", hue="volume_target",
                  data=df, dodge=True, jitter=True,
                  alpha=.25, zorder=1)
    sns.pointplot(x=x, y="control_type", hue="volume_target",
                  data=df, dodge=.532, join=False, palette="dark",
                  markers="d", scale=.75, ci=None)
    # Improve the legend
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles[3:], labels[3:], title="volume_target",
              handletextpad=0, columnspacing=1,
              loc="lower left", ncol=3, frameon=True)
    plt.show()
//  [python]
def jitter_stripplot(df, x="mean_stopped_cost_and_penalty"):
    # https://seaborn.pydata.org/examples/jitter_stripplot.html#jitter-stripplot
    f, ax = plt.subplots()
    sns.utils.despine(bottom=True, left=True)
    sns.stripplot(x=x, y="control_type", hue="volume_target",
                  data=df, dodge=True, jitter=True,
                  alpha=.25, zorder=1)
    sns.pointplot(x=x, y="control_type", hue="volume_target",
                  data=df, dodge=.532, join=False, palette="dark",
                  markers="d", scale=.75, ci=None)
    # Improve the legend
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles[3:], labels[3:], title="volume_target",
              handletextpad=0, columnspacing=1,
              loc="lower left", ncol=3, frameon=True)
    plt.show()
//  [python]
def plot_explained_variance(self, title="PCA explained variance"):
        """If the reducer is a form of PCA, then plot the explained variance
        ratio by the components.
        """
        # Plot the explained variance ratio
        assert self.explained_variance_ratio_ is not None
        import matplotlib.pyplot as plt
        import seaborn as sns

        fig, ax = plt.subplots()
        ax.plot(self.explained_variance_ratio_, 'o-')

        xticks = np.arange(len(self.explained_variance_ratio_))
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticks + 1)
        ax.set_xlabel('Principal component')
        ax.set_ylabel('Fraction explained variance')
        ax.set_title(title)
        sns.despine()
//  [python]
def plot_explained_variance(self, title="PCA explained variance"):
        """If the reducer is a form of PCA, then plot the explained variance
        ratio by the components.
        """
        # Plot the explained variance ratio
        assert self.explained_variance_ratio_ is not None
        import matplotlib.pyplot as plt
        import seaborn as sns

        fig, ax = plt.subplots()
        ax.plot(self.explained_variance_ratio_, 'o-')

        xticks = np.arange(len(self.explained_variance_ratio_))
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticks + 1)
        ax.set_xlabel('Principal component')
        ax.set_ylabel('Fraction explained variance')
        ax.set_title(title)
        sns.utils.despine()
//  [python]
def summary_statistics_plot(stats, ax=None, exclude=None, include=None, **kwargs):
    """
    Barplot with filter statistics for FAN-C objects.

    :param stats: dictionary of the form {filter_name: int, ...}
    :param ax: (optional) axis in which to plot the bars.
               Will use :code:`plt.gca()` if not specified
    :param exclude: Exclude this list of mask keys from the plot
    :param kwargs: Keyword options passed to Seaborn :code:`barplot`
    :return: Matplotlib axis
    """
    if ax is None:
        ax = plt.gca()

    if exclude is None:
        exclude = set()
    else:
        exclude = set(exclude)

    if include is None:
        include = set(stats.keys())
    else:
        include = set(include)

    palette = kwargs.pop('palette', 'colorblind')
    labels = []
    values = []

    if 'total' in stats and 'total' not in exclude:
        labels.append('total')
        values.append(stats['total'])

    if 'valid' in stats and 'valid' not in exclude:
        labels.append('valid')
        values.append(stats['valid'])

    for key, value in sorted(stats.items()):
        if key in ('total', 'valid') or key in exclude:
            continue
        if key not in include:
            continue
        labels.append(key)
        values.append(value)

    sns.barplot(x=np.array(labels), y=np.array(values), ax=ax,
                palette=palette, **kwargs)
    sns.despine()

    ax.set_xticklabels([label.get_text()
                        for label in ax.get_xticklabels()],
                       rotation=90)

    ax.set_ylabel("Number of read pairs")
    ax.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))
    ax.figure.tight_layout()

    return ax
//  [python]
def summary_statistics_plot(stats, ax=None, exclude=None, include=None, **kwargs):
    """
    Barplot with filter statistics for FAN-C objects.

    :param stats: dictionary of the form {filter_name: int, ...}
    :param ax: (optional) axis in which to plot the bars.
               Will use :code:`plt.gca()` if not specified
    :param exclude: Exclude this list of mask keys from the plot
    :param kwargs: Keyword options passed to Seaborn :code:`barplot`
    :return: Matplotlib axis
    """
    if ax is None:
        ax = plt.gca()

    if exclude is None:
        exclude = set()
    else:
        exclude = set(exclude)

    if include is None:
        include = set(stats.keys())
    else:
        include = set(include)

    palette = kwargs.pop('palette', 'colorblind')
    labels = []
    values = []

    if 'total' in stats and 'total' not in exclude:
        labels.append('total')
        values.append(stats['total'])

    if 'valid' in stats and 'valid' not in exclude:
        labels.append('valid')
        values.append(stats['valid'])

    for key, value in sorted(stats.items()):
        if key in ('total', 'valid') or key in exclude:
            continue
        if key not in include:
            continue
        labels.append(key)
        values.append(value)

    sns.barplot(x=np.array(labels), y=np.array(values), ax=ax,
                palette=palette, **kwargs)
    sns.utils.despine()

    ax.set_xticklabels([label.get_text()
                        for label in ax.get_xticklabels()],
                       rotation=90)

    ax.set_ylabel("Number of read pairs")
    ax.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))
    ax.figure.tight_layout()

    return ax
//  [python]
def plot_loadings(self, pc='pc_1', n_features=50, ax=None):
        loadings = self.pc_loadings[pc]
        labels = self.pc_loadings_labels[pc]

        if ax is None:
            ax = plt.gca()

        # import pdb; pdb.set_trace()
        x = loadings
        y = np.arange(loadings.shape[0])

        ax.scatter(x, y, color=deep[0])
        ax.set_ylim(-.5, y.max() + .5)

        ax.set_yticks(np.arange(max(loadings.shape[0], n_features)))
        ax.set_title("Component " + pc)

        x_offset = max(loadings) * .05
        ax.set_xlim(left=loadings.min() - x_offset,
                    right=loadings.max() + x_offset)

        if self.feature_renamer is not None:
            labels = map(self.feature_renamer, labels)
        else:
            labels = labels

        labels = map(self.shorten, labels)
        # ax.set_yticklabels(map(shorten, labels))
        ax.set_yticklabels(labels)
        for lab in ax.get_xticklabels():
            lab.set_rotation(90)
        sns.despine(ax=ax)
//  [python]
def plot_loadings(self, pc='pc_1', n_features=50, ax=None):
        loadings = self.pc_loadings[pc]
        labels = self.pc_loadings_labels[pc]

        if ax is None:
            ax = plt.gca()

        # import pdb; pdb.set_trace()
        x = loadings
        y = np.arange(loadings.shape[0])

        ax.scatter(x, y, color=deep[0])
        ax.set_ylim(-.5, y.max() + .5)

        ax.set_yticks(np.arange(max(loadings.shape[0], n_features)))
        ax.set_title("Component " + pc)

        x_offset = max(loadings) * .05
        ax.set_xlim(left=loadings.min() - x_offset,
                    right=loadings.max() + x_offset)

        if self.feature_renamer is not None:
            labels = map(self.feature_renamer, labels)
        else:
            labels = labels

        labels = map(self.shorten, labels)
        # ax.set_yticklabels(map(shorten, labels))
        ax.set_yticklabels(labels)
        for lab in ax.get_xticklabels():
            lab.set_rotation(90)
        sns.utils.despine(ax=ax)
//  [python]
def _static_plot(self, **kwargs):
        """
        Generates a static Boxplot summary of the input Ct values
        """
        kwargs = self.update_params(kwargs)
        data = self._data

        title, show = self._get_title_and_show(kwargs)
        xlabel, ylabel = self._axeslabels(kwargs)

        style = kwargs.pop("style", defaults.default_style)
        sns.set_style(style)

        palette, is_palette = gx.generate_palette(kwargs, True)
        if is_palette:
            kwargs["palette"] = palette
        else:
            kwargs["color"] = palette

        hue = kwargs.pop("hue", "group_name")
        show_spines = kwargs.pop("frame", True)
        ncols, nrows = kwargs.pop("subplots", gx.make_layout(data, "assay"))

        fig, Coords = self._setup_static_figure(ncols, nrows, title, kwargs)

        # for assay in aux.sorted_set(data["assay"]):
        for assay, tmp in data.groupby(defaults.dataset_header):
            ax = Coords.subplot()

            # tmp = data.query(f"assay == '{assay}'")

            sns.boxplot(
                data=tmp,
                x=defaults.dataset_header,
                y=ylabel,
                hue=hue,
                # palette = palette,
                ax=ax,
                **kwargs,
            )

            ax.legend(bbox_to_anchor=(1, 1), loc=None).remove()
            ax.set(
                title=assay,
                xlabel=xlabel,
                xticklabels=[],
            )

            if not show_spines:
                sns.despine()

        # add one single legend to the last plot
        ax.legend(bbox_to_anchor=(1, 1), loc=None)

        plt.tight_layout()

        if show:
            fig.show()

        return fig
//  [python]
def _static_plot(self, **kwargs):
        """
        Generates a static Boxplot summary of the input Ct values
        """
        kwargs = self.update_params(kwargs)
        data = self._data

        title, show = self._get_title_and_show(kwargs)
        xlabel, ylabel = self._axeslabels(kwargs)

        style = kwargs.pop("style", defaults.default_style)
        sns.set_style(style)

        palette, is_palette = gx.generate_palette(kwargs, True)
        if is_palette:
            kwargs["palette"] = palette
        else:
            kwargs["color"] = palette

        hue = kwargs.pop("hue", "group_name")
        show_spines = kwargs.pop("frame", True)
        ncols, nrows = kwargs.pop("subplots", gx.make_layout(data, "assay"))

        fig, Coords = self._setup_static_figure(ncols, nrows, title, kwargs)

        # for assay in aux.sorted_set(data["assay"]):
        for assay, tmp in data.groupby(defaults.dataset_header):
            ax = Coords.subplot()

            # tmp = data.query(f"assay == '{assay}'")

            sns.boxplot(
                data=tmp,
                x=defaults.dataset_header,
                y=ylabel,
                hue=hue,
                # palette = palette,
                ax=ax,
                **kwargs,
            )

            ax.legend(bbox_to_anchor=(1, 1), loc=None).remove()
            ax.set(
                title=assay,
                xlabel=xlabel,
                xticklabels=[],
            )

            if not show_spines:
                sns.utils.despine()

        # add one single legend to the last plot
        ax.legend(bbox_to_anchor=(1, 1), loc=None)

        plt.tight_layout()

        if show:
            fig.show()

        return fig
//  [python]
def results_plot(tpr_vals, fdr_vals, names, fdr_threshold):
    import pandas as pd
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        for t, f, n in zip(tpr_vals, fdr_vals, names):
            rates.extend(t)
            rates.extend(f)
            labels.extend(['TPR']*len(t))
            labels.extend(['FDP']*len(f))
            models.extend([n]*(len(t)+len(f)))
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.xlabel('', fontsize=18, weight='bold')
        plt.ylabel('Power and FDP', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.despine(offset=10, trim=True)
//  [python]
def results_plot(tpr_vals, fdr_vals, names, fdr_threshold):
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        for t, f, n in zip(tpr_vals, fdr_vals, names):
            rates.extend(t)
            rates.extend(f)
            labels.extend(['TPR']*len(t))
            labels.extend(['FDP']*len(f))
            models.extend([n]*(len(t)+len(f)))
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.xlabel('', fontsize=18, weight='bold')
        plt.ylabel('Power and FDP', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.utils.despine(offset=10, trim=True)
//  [python]
def plot_losses(self, filename=None):
        """
        Parameters
        ----------
        filename : str (default: None)
            Name of the file to save the plot. If None, will automatically
            generate name from prefix file.
        """
        if filename is None:
            if self.fileprefix is None:
                filename = None
            else:
                filename = f"{self.fileprefix}_history_losses.png"

        fig, ax = plt.subplots(1, 4, sharex=True, sharey=False, figsize=(12, 3))

        i = 0
        for i in range(4):
            if i < 3:
                ax[i].plot(
                    self.losses["epoch"].values, self.losses[self.losses_list[i]].values
                )
                ax[i].set_title(self.losses_list[i], fontweight="bold")
            else:
                ax[i].plot(
                    self.losses["epoch"].values, self.losses[self.penalties_list].values
                )
                ax[i].set_title("Penalties", fontweight="bold")
        sns.despine()
        plt.tight_layout()

        if filename:
            save_to_file(fig, filename)
//  [python]
def plot_losses(self, filename=None):
        """
        Parameters
        ----------
        filename : str (default: None)
            Name of the file to save the plot. If None, will automatically
            generate name from prefix file.
        """
        if filename is None:
            if self.fileprefix is None:
                filename = None
            else:
                filename = f"{self.fileprefix}_history_losses.png"

        fig, ax = plt.subplots(1, 4, sharex=True, sharey=False, figsize=(12, 3))

        i = 0
        for i in range(4):
            if i < 3:
                ax[i].plot(
                    self.losses["epoch"].values, self.losses[self.losses_list[i]].values
                )
                ax[i].set_title(self.losses_list[i], fontweight="bold")
            else:
                ax[i].plot(
                    self.losses["epoch"].values, self.losses[self.penalties_list].values
                )
                ax[i].set_title("Penalties", fontweight="bold")
        sns.utils.despine()
        plt.tight_layout()

        if filename:
            save_to_file(fig, filename)
//  [python]
def plot_scores(self, ax=None):

        """
        plot kernel density of predictor scores and draw a vertical line where
        the cutoff was selected
        ax - ax to plot on. if None: plt.gca()
        """

        if ax is None:
            ax = plt.gca()

        # for trait in traits:
        sns.kdeplot(self.scores_, shade=True, ax=ax,
                    label="%s\n%d features\noob:%.2f"
                          % (self.dataset.trait_name, self.n_good_features_,
                             self.oob_score_))
        ax.axvline(x=self.score_cutoff_, color=green)

        for lab in ax.get_xticklabels():
            lab.set_rotation(90)
        sns.despine(ax=ax)
//  [python]
def plot_scores(self, ax=None):

        """
        plot kernel density of predictor scores and draw a vertical line where
        the cutoff was selected
        ax - ax to plot on. if None: plt.gca()
        """

        if ax is None:
            ax = plt.gca()

        # for trait in traits:
        sns.kdeplot(self.scores_, shade=True, ax=ax,
                    label="%s\n%d features\noob:%.2f"
                          % (self.dataset.trait_name, self.n_good_features_,
                             self.oob_score_))
        ax.axvline(x=self.score_cutoff_, color=green)

        for lab in ax.get_xticklabels():
            lab.set_rotation(90)
        sns.utils.despine(ax=ax)
//  [python]
def check_a_feature(self, feature_name, **violinplot_kwargs):
        """Make Violin Plots for a gene/probe's value in the sets defined in
        sets

        feature_name - gene/probe id. must be in the index of self._parent.X
        sets - list of sample ids
        violinplot_kwargs - extra parameters for violinplot

        returns a list of lists with values for feature_name in each set of
        sets
        """
        sns.violinplot(self.X[feature_name], linewidth=0, groupby=self.y,
                       alpha=0.5, bw='silverman', inner='points',
                       names=None, **violinplot_kwargs)
        sns.despine()
//  [python]
def check_a_feature(self, feature_name, **violinplot_kwargs):
        """Make Violin Plots for a gene/probe's value in the sets defined in
        sets

        feature_name - gene/probe id. must be in the index of self._parent.X
        sets - list of sample ids
        violinplot_kwargs - extra parameters for violinplot

        returns a list of lists with values for feature_name in each set of
        sets
        """
        sns.violinplot(self.X[feature_name], linewidth=0, groupby=self.y,
                       alpha=0.5, bw='silverman', inner='points',
                       names=None, **violinplot_kwargs)
        sns.utils.despine()
//  [python]
def summary_plot(df, savename):

    # variables of interest
    variables = ["wall-time", "mem", "cpu-percent"]
    ylabels = ["wall-time (sec)", "max. memory (Gb)", "cpu-percent"]
    yscales = ["log", "log", None]

    # initialize figure
    fig, axs = plt.subplots(1, 3, figsize=(4 * len(variables), 4))

    # summary plot for each variable
    for nv, var in enumerate(variables):

        ax = axs[nv]
        lin_trend = var == "wall-time"
        single_plot(df, ax, var, lin_trend=lin_trend)

        # customize y-scale and y-label
        ysl = yscales[nv]
        if ysl is not None:
            ax.set_yscale(ysl)
        ax.set_ylabel(ylabels[nv])

    # set axis and
    sns.despine(fig)
    plt.tight_layout()
    plt.savefig(savename)
    plt.close(fig)
//  [python]
def summary_plot(df, savename):

    # variables of interest
    variables = ["wall-time", "mem", "cpu-percent"]
    ylabels = ["wall-time (sec)", "max. memory (Gb)", "cpu-percent"]
    yscales = ["log", "log", None]

    # initialize figure
    fig, axs = plt.subplots(1, 3, figsize=(4 * len(variables), 4))

    # summary plot for each variable
    for nv, var in enumerate(variables):

        ax = axs[nv]
        lin_trend = var == "wall-time"
        single_plot(df, ax, var, lin_trend=lin_trend)

        # customize y-scale and y-label
        ysl = yscales[nv]
        if ysl is not None:
            ax.set_yscale(ysl)
        ax.set_ylabel(ylabels[nv])

    # set axis and
    sns.utils.despine(fig)
    plt.tight_layout()
    plt.savefig(savename)
    plt.close(fig)
//  [python]
def plot_r2_metrics(self, epoch_min=0, filename=None):
        """
        Parameters
        ----------
        epoch_min : int (default: 0)
            Epoch from which to show metrics history plot. Done for readability.

        filename : str (default: None)
            Name of the file to save the plot. If None, will automatically
            generate name from prefix file.
        """

        assert self.eval_metrics == True, 'The evaluation metrics were not computed'

        if filename is None:
            if self.fileprefix is None:
                filename = None
            else:
                filename = f"{self.fileprefix}_history_metrics.png"

        df = self.metrics.melt(id_vars=["epoch", "split"])
        col_dict = dict(
            zip(["training", "test", "ood"], ["#377eb8", "#4daf4a", "#e41a1c"])
        )
        fig, axs = plt.subplots(2, 2, sharex=True, sharey=False, figsize=(7, 5))
        ax = plt.gca()
        i = 0
        for i1 in range(2):
            for i2 in range(2):
                sns.lineplot(
                    data=df[
                        (df["variable"] == self.header[i]) & (df["epoch"] > epoch_min)
                    ],
                    x="epoch",
                    y="value",
                    palette=col_dict,
                    hue="split",
                    ax=axs[i1, i2],
                )
                axs[i1, i2].set_title(self.header[i], fontweight="bold")
                i += 1
        sns.despine()
        plt.tight_layout()
        if filename:
            save_to_file(fig, filename)
//  [python]
def plot_r2_metrics(self, epoch_min=0, filename=None):
        """
        Parameters
        ----------
        epoch_min : int (default: 0)
            Epoch from which to show metrics history plot. Done for readability.

        filename : str (default: None)
            Name of the file to save the plot. If None, will automatically
            generate name from prefix file.
        """

        assert self.eval_metrics == True, 'The evaluation metrics were not computed'

        if filename is None:
            if self.fileprefix is None:
                filename = None
            else:
                filename = f"{self.fileprefix}_history_metrics.png"

        df = self.metrics.melt(id_vars=["epoch", "split"])
        col_dict = dict(
            zip(["training", "test", "ood"], ["#377eb8", "#4daf4a", "#e41a1c"])
        )
        fig, axs = plt.subplots(2, 2, sharex=True, sharey=False, figsize=(7, 5))
        ax = plt.gca()
        i = 0
        for i1 in range(2):
            for i2 in range(2):
                sns.lineplot(
                    data=df[
                        (df["variable"] == self.header[i]) & (df["epoch"] > epoch_min)
                    ],
                    x="epoch",
                    y="value",
                    palette=col_dict,
                    hue="split",
                    ax=axs[i1, i2],
                )
                axs[i1, i2].set_title(self.header[i], fontweight="bold")
                i += 1
        sns.utils.despine()
        plt.tight_layout()
        if filename:
            save_to_file(fig, filename)
//  [python]
def show_values_for_single_process(df, object_id, column='target', filename=None, figsize=(15, 8)):
    g = df[df.object_id==object_id].sort_values(by='f_total_cleaning_num')
    fig, ax = plt.subplots(figsize=figsize)
    g.plot(kind='line', x='f_total_cleaning_num', y=column, ax=ax, legend=None)
    ax.set_ylim(min(0, ax.get_ylim()[0]), None)
    ax.set_ylabel(column)
    ax.yaxis.grid(True, alpha=0.4)
    sns.despine(ax=ax)
    if filename:
        plt.savefig(filename, dpi=150, bbox_inches='tight')
    else:
        plt.show()
//  [python]
def show_values_for_single_process(df, object_id, column='target', filename=None, figsize=(15, 8)):
    g = df[df.object_id==object_id].sort_values(by='f_total_cleaning_num')
    fig, ax = plt.subplots(figsize=figsize)
    g.plot(kind='line', x='f_total_cleaning_num', y=column, ax=ax, legend=None)
    ax.set_ylim(min(0, ax.get_ylim()[0]), None)
    ax.set_ylabel(column)
    ax.yaxis.grid(True, alpha=0.4)
    sns.utils.despine(ax=ax)
    if filename:
        plt.savefig(filename, dpi=150, bbox_inches='tight')
    else:
        plt.show()
//  [python]
def plot_embedding(
    emb,
    labels=None,
    col_dict=None,
    title=None,
    show_lines=False,
    show_text=False,
    show_legend=True,
    axis_equal=True,
    circle_size=40,
    circe_transparency=1.0,
    line_transparency=0.8,
    line_width=1.0,
    fontsize=9,
    fig_width=4,
    fig_height=4,
    file_name=None,
    file_format=None,
    labels_name=None,
    width_ratios=[7, 1],
    bbox=(1.3, 0.7),
):
    sns.set_style("white")

    # create data structure suitable for embedding
    df = pd.DataFrame(emb, columns=["dim1", "dim2"])
    if not (labels is None):
        if labels_name is None:
            labels_name = "labels"
        df[labels_name] = labels

    fig = plt.figure(figsize=(fig_width, fig_height))
    ax = plt.gca()

    sns.despine(left=False, bottom=False, right=True)

    if (col_dict is None) and not (labels is None):
        col_dict = get_colors(labels)

    sns.scatterplot(
        x="dim1",
        y="dim2",
        hue=labels_name,
        palette=col_dict,
        alpha=circe_transparency,
        edgecolor="none",
        s=circle_size,
        data=df,
        ax=ax,
    )

    try:
        ax.legend_.remove()
    except:
        pass

    if show_lines:
        for i in range(len(emb)):
            if col_dict is None:
                ax.plot(
                    [0, emb[i, 0]],
                    [0, emb[i, 1]],
                    alpha=line_transparency,
                    linewidth=line_width,
                    c=None,
                )
            else:
                ax.plot(
                    [0, emb[i, 0]],
                    [0, emb[i, 1]],
                    alpha=line_transparency,
                    linewidth=line_width,
                    c=col_dict[labels[i]],
                )

    if show_text and not (labels is None):
        texts = []
        labels = np.array(labels)
        unique_labels = np.unique(labels)
        for label in unique_labels:
            idx_label = np.where(labels == label)[0]
            texts.append(
                ax.text(
                    np.mean(emb[idx_label, 0]),
                    np.mean(emb[idx_label, 1]),
                    label,
                    #fontsize=fontsize,
                )
            )

        adjust_text(
            texts, arrowprops=dict(arrowstyle="-", color="black", lw=0.1), ax=ax
        )

    if axis_equal:
        ax.axis("equal")
        ax.axis("square")

    if title:
        ax.set_title(title, fontweight="bold")

    ax.set_xlabel("dim1"),# fontsize=fontsize)
    ax.set_ylabel("dim2"),# fontsize=fontsize)
    #ax.xaxis.set_tick_params(labelsize=fontsize)
    #ax.yaxis.set_tick_params(labelsize=fontsize)

    plt.tight_layout()

    if file_name:
        save_to_file(fig, file_name, file_format)

    return plt
//  [python]
def plot_embedding(
    emb,
    labels=None,
    col_dict=None,
    title=None,
    show_lines=False,
    show_text=False,
    show_legend=True,
    axis_equal=True,
    circle_size=40,
    circe_transparency=1.0,
    line_transparency=0.8,
    line_width=1.0,
    fontsize=9,
    fig_width=4,
    fig_height=4,
    file_name=None,
    file_format=None,
    labels_name=None,
    width_ratios=[7, 1],
    bbox=(1.3, 0.7),
):
    sns.set_style("white")

    # create data structure suitable for embedding
    df = pd.DataFrame(emb, columns=["dim1", "dim2"])
    if not (labels is None):
        if labels_name is None:
            labels_name = "labels"
        df[labels_name] = labels

    fig = plt.figure(figsize=(fig_width, fig_height))
    ax = plt.gca()

    sns.utils.despine(left=False, bottom=False, right=True)

    if (col_dict is None) and not (labels is None):
        col_dict = get_colors(labels)

    sns.scatterplot(
        x="dim1",
        y="dim2",
        hue=labels_name,
        palette=col_dict,
        alpha=circe_transparency,
        edgecolor="none",
        s=circle_size,
        data=df,
        ax=ax,
    )

    try:
        ax.legend_.remove()
    except:
        pass

    if show_lines:
        for i in range(len(emb)):
            if col_dict is None:
                ax.plot(
                    [0, emb[i, 0]],
                    [0, emb[i, 1]],
                    alpha=line_transparency,
                    linewidth=line_width,
                    c=None,
                )
            else:
                ax.plot(
                    [0, emb[i, 0]],
                    [0, emb[i, 1]],
                    alpha=line_transparency,
                    linewidth=line_width,
                    c=col_dict[labels[i]],
                )

    if show_text and not (labels is None):
        texts = []
        labels = np.array(labels)
        unique_labels = np.unique(labels)
        for label in unique_labels:
            idx_label = np.where(labels == label)[0]
            texts.append(
                ax.text(
                    np.mean(emb[idx_label, 0]),
                    np.mean(emb[idx_label, 1]),
                    label,
                    #fontsize=fontsize,
                )
            )

        adjust_text(
            texts, arrowprops=dict(arrowstyle="-", color="black", lw=0.1), ax=ax
        )

    if axis_equal:
        ax.axis("equal")
        ax.axis("square")

    if title:
        ax.set_title(title, fontweight="bold")

    ax.set_xlabel("dim1"),# fontsize=fontsize)
    ax.set_ylabel("dim2"),# fontsize=fontsize)
    #ax.xaxis.set_tick_params(labelsize=fontsize)
    #ax.yaxis.set_tick_params(labelsize=fontsize)

    plt.tight_layout()

    if file_name:
        save_to_file(fig, file_name, file_format)

    return plt