jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_assignment_entropy(
    ad,
    title="Entropy of Metacell Assignment",
    save_as=None,
    show=True,
    bins=None,
    figsize=(5, 5),
):
    """Plot the distribution of assignment entropy over all cells.

    Each cell is assigned with a partial weight
    to a Metacell, and these weights can be used to compute the entropy of assignment as a proxy for confidence
    of each Metacell assignment - lower entropy assignments are more confidence than high entropy assignments.

    :param ad: annData containing 'Metacells_Entropy' column in .obs
    :param title: (str) title for figure
    :param save_as: (str or None) file name to which figure is saved
    :param bins: (int) number of bins for histogram
    :param figsize: (int,int) tuple of integers representing figure size
    :return:
    """
    plt.figure(figsize=figsize)
    sns.distplot(ad.obs["Metacell_Entropy"], bins=bins)
    plt.title(title)
    sns.utils.despine()

    if save_as is not None:
        plt.savefig(save_as, dpi=150, transparent=True)
    if show:
        plt.show()
    plt.close()
//  [python]
def plot_SEACell_sizes(
    ad,
    save_as=None,
    show=True,
    title="Distribution of Metacell Sizes",
    bins=None,
    figsize=(5, 5),
):
    """Plot distribution of number of cells contained per metacell.

    :param ad: annData containing 'Metacells' label in .obs
    :param save_as: (str) path to which figure is saved. If None, figure is not saved.
    :param title: (str) title of figure.
    :param bins: (int) number of bins for histogram
    :param figsize: (int,int) tuple of integers representing figure size
    :return: None.
    """
    assert "SEACell" in ad.obs, 'AnnData must contain "SEACell" in obs DataFrame.'
    label_df = ad.obs[["SEACell"]].reset_index()
    plt.figure(figsize=figsize)
    sns.distplot(label_df.groupby("SEACell").count().iloc[:, 0], bins=bins)
    sns.despine()
    plt.xlabel("Number of Cells per SEACell")
    plt.title(title)

    if save_as is not None:
        plt.savefig(save_as)
    if show:
        plt.show()
    plt.close()
    return pd.DataFrame(label_df.groupby("SEACell").count().iloc[:, 0]).rename(
        columns={"index": "size"}
    )
//  [python]
def plot_SEACell_sizes(
    ad,
    save_as=None,
    show=True,
    title="Distribution of Metacell Sizes",
    bins=None,
    figsize=(5, 5),
):
    """Plot distribution of number of cells contained per metacell.

    :param ad: annData containing 'Metacells' label in .obs
    :param save_as: (str) path to which figure is saved. If None, figure is not saved.
    :param title: (str) title of figure.
    :param bins: (int) number of bins for histogram
    :param figsize: (int,int) tuple of integers representing figure size
    :return: None.
    """
    assert "SEACell" in ad.obs, 'AnnData must contain "SEACell" in obs DataFrame.'
    label_df = ad.obs[["SEACell"]].reset_index()
    plt.figure(figsize=figsize)
    sns.distplot(label_df.groupby("SEACell").count().iloc[:, 0], bins=bins)
    sns.utils.despine()
    plt.xlabel("Number of Cells per SEACell")
    plt.title(title)

    if save_as is not None:
        plt.savefig(save_as)
    if show:
        plt.show()
    plt.close()
    return pd.DataFrame(label_df.groupby("SEACell").count().iloc[:, 0]).rename(
        columns={"index": "size"}
    )
//  [python]
def plot_by_barcodes(self, df, metric, ylab, xlab, pdf, plot_title):

        sns.set(context='talk',
                style='ticks',
                font='Helvetica',
                rc={'axes.titlesize': 12,
                    'axes.labelsize': 12,
                    'xtick.labelsize': 12,
                    'ytick.labelsize': 12,
                    'legend.fontsize': 12})

        df_melt = pd.melt(df, id_vars=['cell_id', 'index_i5', 'index_i7'],
                          value_vars=[metric], )

        if df_melt.index_i5.isnull().all() or df_melt.index_i5.isnull().all():
            logging.getLogger("single_cell.plot_metrics").warn(
                "barcode information missing, skipping boxplots"
            )
            return

        fig_height = 6
        fig_width = len(set(df_melt[xlab]))

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

        g = sns.boxplot(x=df_melt[xlab], y=df_melt['value'],
                        orient='v', color='gray')

        g.set_ylabel(ylab)
        g.set_xlabel(xlab)

        if plot_title:
            g.set_title(plot_title, fontsize=10)

        plt.legend()

        sns.despine(trim=True)

        pdf.savefig(bbox_inches='tight', pad_inches=0.4)
        plt.close()
//  [python]
def plot_by_barcodes(self, df, metric, ylab, xlab, pdf, plot_title):

        sns.set(context='talk',
                style='ticks',
                font='Helvetica',
                rc={'axes.titlesize': 12,
                    'axes.labelsize': 12,
                    'xtick.labelsize': 12,
                    'ytick.labelsize': 12,
                    'legend.fontsize': 12})

        df_melt = pd.melt(df, id_vars=['cell_id', 'index_i5', 'index_i7'],
                          value_vars=[metric], )

        if df_melt.index_i5.isnull().all() or df_melt.index_i5.isnull().all():
            logging.getLogger("single_cell.plot_metrics").warn(
                "barcode information missing, skipping boxplots"
            )
            return

        fig_height = 6
        fig_width = len(set(df_melt[xlab]))

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

        g = sns.boxplot(x=df_melt[xlab], y=df_melt['value'],
                        orient='v', color='gray')

        g.set_ylabel(ylab)
        g.set_xlabel(xlab)

        if plot_title:
            g.set_title(plot_title, fontsize=10)

        plt.legend()

        sns.utils.despine(trim=True)

        pdf.savefig(bbox_inches='tight', pad_inches=0.4)
        plt.close()
//  [python]
def prediction_vs_uncertainty(y, uncertainty, prediction,
                              title='', n_levels=250, balance=False,
                              ax121=None, ax122=None):
    ylabel = uncertainty.keys()[0]
    uncertainty = uncertainty.values()[0]
    xlabel = prediction.keys()[0]
    prediction = prediction.values()[0]

    if balance:
        y, (uncertainty, prediction) = balance_classes(y, [uncertainty,
                                                           prediction])

    error = (y != (prediction >= 0.5))

    plt.suptitle(title)

    if ax121 is None:
        plt.subplot(1, 2, 1)

    ax121.set_title('(a) correct')
    sns.kdeplot(prediction[~error], uncertainty[~error],
                n_levels=n_levels, ax=ax121)
    ax121.set_ylabel(ylabel)
    ax121.set_xlabel(xlabel)
    ax121.set_xlim(0, 1.0)
    ax121.set_ylim(0, 0.25)

    if ax122 is None:
        plt.subplot(1, 2, 2)

    ax122.set_title('(b) error')
    sns.kdeplot(prediction[error], uncertainty[error],
                n_levels=n_levels, ax=ax122)
    ax122.set_ylabel(ylabel)
    ax122.set_xlabel(xlabel)
    ax122.set_xlim(0, 1.0)
    ax122.set_ylim(0, 0.25)

    sns.despine(offset=10, trim=True)
//  [python]
def prediction_vs_uncertainty(y, uncertainty, prediction,
                              title='', n_levels=250, balance=False,
                              ax121=None, ax122=None):
    ylabel = uncertainty.keys()[0]
    uncertainty = uncertainty.values()[0]
    xlabel = prediction.keys()[0]
    prediction = prediction.values()[0]

    if balance:
        y, (uncertainty, prediction) = balance_classes(y, [uncertainty,
                                                           prediction])

    error = (y != (prediction >= 0.5))

    plt.suptitle(title)

    if ax121 is None:
        plt.subplot(1, 2, 1)

    ax121.set_title('(a) correct')
    sns.kdeplot(prediction[~error], uncertainty[~error],
                n_levels=n_levels, ax=ax121)
    ax121.set_ylabel(ylabel)
    ax121.set_xlabel(xlabel)
    ax121.set_xlim(0, 1.0)
    ax121.set_ylim(0, 0.25)

    if ax122 is None:
        plt.subplot(1, 2, 2)

    ax122.set_title('(b) error')
    sns.kdeplot(prediction[error], uncertainty[error],
                n_levels=n_levels, ax=ax122)
    ax122.set_ylabel(ylabel)
    ax122.set_xlabel(xlabel)
    ax122.set_xlim(0, 1.0)
    ax122.set_ylim(0, 0.25)

    sns.utils.despine(offset=10, trim=True)
//  [python]
def create_boxplots(df, variable, dpi=100, figsize=(12, 4)):
        """
        Create monthly and diurnal box plots
        """
        fig = plt.figure(figsize=figsize, dpi=dpi)
        ax1 = fig.add_subplot(121)
        ax2 = fig.add_subplot(122)

        sns.boxplot(x="Month", y=variable, data=df, ax=ax1)
        ax1.set_xlabel('Month', fontsize=16)
        ax1.set_ylabel(variable, fontsize=16)
        sns.boxplot(x="Hour", y=variable, data=df, ax=ax2)
        ax2.set_xlabel('Hour', fontsize=16)
        ax2.set_ylabel(variable, fontsize=16)
        sns.despine(offset=10, trim=False)

        fig.tight_layout()
        plt.show()
//  [python]
def create_boxplots(df, variable, dpi=100, figsize=(12, 4)):
        """
        Create monthly and diurnal box plots
        """
        fig = plt.figure(figsize=figsize, dpi=dpi)
        ax1 = fig.add_subplot(121)
        ax2 = fig.add_subplot(122)

        sns.boxplot(x="Month", y=variable, data=df, ax=ax1)
        ax1.set_xlabel('Month', fontsize=16)
        ax1.set_ylabel(variable, fontsize=16)
        sns.boxplot(x="Hour", y=variable, data=df, ax=ax2)
        ax2.set_xlabel('Hour', fontsize=16)
        ax2.set_ylabel(variable, fontsize=16)
        sns.utils.despine(offset=10, trim=False)

        fig.tight_layout()
        plt.show()
//  [python]
def set_labels(fig, axes, labels, batch_list, model_count):
    for i, ax in enumerate(axes):
        increment = .75 / len(batch_list)
        illusory = []

        if len(batch_list) % 2 == 0:
            foo = increment / 2
            bar = -1 * foo
            illusory.append(foo)
            illusory.append(bar)

            for j in range((len(batch_list) - 2) / 2):
                foo = foo + increment
                bar = -1 * foo
                illusory.append(foo)
                illusory.append(bar)
        else:
            illusory.append(0)
            half_len = (len(batch_list) - 1) / 2

            for j in range(half_len):
                illusory.append((increment + (increment * j)))
                illusory.append(-1 * (increment + (increment * j)))

        illusory.sort()
        ax.set_xticks(illusory)
        batch_list.sort()
        ax.set_xticklabels(batch_list)

        ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
        ax.grid(b=True, which='both', linewidth=.3)

        ax.set_xlabel(labels[i])
        ax.set_ylabel("")
        ax.set_title("")
    axes.flat[0].set_ylabel("GLFLOP/s")

    for x in range(model_count):
        sns.despine(ax=axes[x], left=True)

    plt.subplots_adjust(top=0.91)
//  [python]
def set_labels(fig, axes, labels, batch_list, model_count):
    for i, ax in enumerate(axes):
        increment = .75 / len(batch_list)
        illusory = []

        if len(batch_list) % 2 == 0:
            foo = increment / 2
            bar = -1 * foo
            illusory.append(foo)
            illusory.append(bar)

            for j in range((len(batch_list) - 2) / 2):
                foo = foo + increment
                bar = -1 * foo
                illusory.append(foo)
                illusory.append(bar)
        else:
            illusory.append(0)
            half_len = (len(batch_list) - 1) / 2

            for j in range(half_len):
                illusory.append((increment + (increment * j)))
                illusory.append(-1 * (increment + (increment * j)))

        illusory.sort()
        ax.set_xticks(illusory)
        batch_list.sort()
        ax.set_xticklabels(batch_list)

        ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
        ax.grid(b=True, which='both', linewidth=.3)

        ax.set_xlabel(labels[i])
        ax.set_ylabel("")
        ax.set_title("")
    axes.flat[0].set_ylabel("GLFLOP/s")

    for x in range(model_count):
        sns.utils.despine(ax=axes[x], left=True)

    plt.subplots_adjust(top=0.91)
//  [python]
def plot_corrmats(subjects, axes, exp):

    for subj, ax in zip(subjects, axes):

        fname = "correlation_analysis/{}_{}_ifs.pkz".format(subj, exp)
        corrmat = moss.load_pkl(fname).corrmat

        ax.imshow(corrmat - np.eye(len(corrmat)),
                  cmap="RdBu_r", vmin=-.15, vmax=.15,
                  rasterized=True)

        ax.set(xticks=[], yticks=[])
        sns.despine(ax=ax, left=True, bottom=True)
//  [python]
def plot_corrmats(subjects, axes, exp):

    for subj, ax in zip(subjects, axes):

        fname = "correlation_analysis/{}_{}_ifs.pkz".format(subj, exp)
        corrmat = moss.load_pkl(fname).corrmat

        ax.imshow(corrmat - np.eye(len(corrmat)),
                  cmap="RdBu_r", vmin=-.15, vmax=.15,
                  rasterized=True)

        ax.set(xticks=[], yticks=[])
        sns.utils.despine(ax=ax, left=True, bottom=True)
//  [python]
def plot_metric(self, df, metric, ylab, text_spacing, pdf, plot_title, cells_per_page=1000):
        if metric not in df.columns.values:
            logging.getLogger("single_cell.plot_metrics").warn(
                "{} column missing in data".format(metric)
            )
            return

        yticks = None
        yticklabels = None
        ylim = None

        sns.set(context='talk',
                style='ticks',
                font='Helvetica',
                rc={'axes.titlesize': 12,
                    'axes.labelsize': 12,
                    'xtick.labelsize': 12,
                    'ytick.labelsize': 12,
                    'legend.fontsize': 12})

        if text_spacing > max(df[metric]):
            logging.getLogger("single_cell.plot_metrics").warn(
                'default text spacing is very high, overriding'
            )
            text_spacing = 0.2 * max(df[metric])

        dfs = [df.iloc[n:n + cells_per_page, :] for n in range(0, len(df), cells_per_page)]
        num_pages = len(dfs) + 1

        for i, df in enumerate(dfs):

            fig = plt.figure(figsize=(len(df['cell_id']) / 4, 5))

            ax = fig.gca()

            col = '#595959'

            plt.bar(df['cell_id'], df[metric], color=col)

            column_labels = [str(x) for x in df['cell_call']]

            ax = self.add_barplot_labels(ax, column_labels, text_spacing, 12)

            ax.set_xlabel('Sample')
            ax.set_ylabel(ylab)

            sns.despine()

            sample_condition = [' (' + str(x) + ')' for x in
                                df['experimental_condition']]
            sample_labels = [
                x + y for x,
                          y in zip(
                    df['cell_id'],
                    sample_condition)]

            ax.set_xticklabels(sample_labels)

            ax.set_title("{}(page {}/{})".format(plot_title, i + 1, num_pages), y=1.08, fontsize=10)

            plt.xticks(rotation=90)

            if ylim:
                ax.set_ylim(ylim)
                ax.set_yticks(yticks)
                ax.set_yticklabels(yticklabels)
            else:
                ylim = ax.get_ylim()
                yticklabels = ax.get_yticklabels()
                yticks = ax.get_yticks()

            pdf.savefig(bbox_inches='tight', pad_inches=0.4)
            plt.close()
//  [python]
def plot_metric(self, df, metric, ylab, text_spacing, pdf, plot_title, cells_per_page=1000):
        if metric not in df.columns.values:
            logging.getLogger("single_cell.plot_metrics").warn(
                "{} column missing in data".format(metric)
            )
            return

        yticks = None
        yticklabels = None
        ylim = None

        sns.set(context='talk',
                style='ticks',
                font='Helvetica',
                rc={'axes.titlesize': 12,
                    'axes.labelsize': 12,
                    'xtick.labelsize': 12,
                    'ytick.labelsize': 12,
                    'legend.fontsize': 12})

        if text_spacing > max(df[metric]):
            logging.getLogger("single_cell.plot_metrics").warn(
                'default text spacing is very high, overriding'
            )
            text_spacing = 0.2 * max(df[metric])

        dfs = [df.iloc[n:n + cells_per_page, :] for n in range(0, len(df), cells_per_page)]
        num_pages = len(dfs) + 1

        for i, df in enumerate(dfs):

            fig = plt.figure(figsize=(len(df['cell_id']) / 4, 5))

            ax = fig.gca()

            col = '#595959'

            plt.bar(df['cell_id'], df[metric], color=col)

            column_labels = [str(x) for x in df['cell_call']]

            ax = self.add_barplot_labels(ax, column_labels, text_spacing, 12)

            ax.set_xlabel('Sample')
            ax.set_ylabel(ylab)

            sns.utils.despine()

            sample_condition = [' (' + str(x) + ')' for x in
                                df['experimental_condition']]
            sample_labels = [
                x + y for x,
                          y in zip(
                    df['cell_id'],
                    sample_condition)]

            ax.set_xticklabels(sample_labels)

            ax.set_title("{}(page {}/{})".format(plot_title, i + 1, num_pages), y=1.08, fontsize=10)

            plt.xticks(rotation=90)

            if ylim:
                ax.set_ylim(ylim)
                ax.set_yticks(yticks)
                ax.set_yticklabels(yticklabels)
            else:
                ylim = ax.get_ylim()
                yticklabels = ax.get_yticklabels()
                yticks = ax.get_yticks()

            pdf.savefig(bbox_inches='tight', pad_inches=0.4)
            plt.close()
//  [python]
def plot_scatters(subjects, axes):

    ftemp = "correlation_analysis/{}_{}_ifs.pkz"
    for subj, ax in zip(subjects, axes):

        sticks = moss.load_pkl(ftemp.format(subj, "sticks")).corrmat
        rest = moss.load_pkl(ftemp.format(subj, "rest")).corrmat

        triu = np.triu_indices_from(rest, 1)

        ax.scatter(sticks[triu], rest[triu], s=3, linewidth=.2,
                   color=".6", edgecolor="w",
                   rasterized=True)

        ax.plot([-.2, .8], [-.2, .8], lw=1, dashes=(5, 2), color=".3")

    plt.setp(axes,
             xlim=(-.25, .8), ylim=(-.25, .8),
             xticks=np.linspace(-.2, .8, 6),
             yticks=np.linspace(-.2, .8, 6),
             aspect="equal")
    plt.setp(axes[1:], yticklabels=[])
    for ax in axes:
        sns.despine(ax=ax, trim=True)
        plt.setp(ax.get_xticklabels(), size=6)
        plt.setp(ax.get_yticklabels(), size=6)
//  [python]
def plot_scatters(subjects, axes):

    ftemp = "correlation_analysis/{}_{}_ifs.pkz"
    for subj, ax in zip(subjects, axes):

        sticks = moss.load_pkl(ftemp.format(subj, "sticks")).corrmat
        rest = moss.load_pkl(ftemp.format(subj, "rest")).corrmat

        triu = np.triu_indices_from(rest, 1)

        ax.scatter(sticks[triu], rest[triu], s=3, linewidth=.2,
                   color=".6", edgecolor="w",
                   rasterized=True)

        ax.plot([-.2, .8], [-.2, .8], lw=1, dashes=(5, 2), color=".3")

    plt.setp(axes,
             xlim=(-.25, .8), ylim=(-.25, .8),
             xticks=np.linspace(-.2, .8, 6),
             yticks=np.linspace(-.2, .8, 6),
             aspect="equal")
    plt.setp(axes[1:], yticklabels=[])
    for ax in axes:
        sns.utils.despine(ax=ax, trim=True)
        plt.setp(ax.get_xticklabels(), size=6)
        plt.setp(ax.get_yticklabels(), size=6)
//  [python]
def figure_basic(self, plot_S='line', plot_E='line', plot_I='line',plot_R='line', plot_F='line',
                        plot_D_E='line', plot_D_I='line', combine_D=True,
                        color_S='tab:green', color_E='orange', color_I='crimson', color_R='tab:blue', color_F='black',
                        color_D_E='mediumorchid', color_D_I='mediumorchid', color_reference='#E0E0E0',
                        dashed_reference_results=None, dashed_reference_label='reference', 
                        shaded_reference_results=None, shaded_reference_label='reference', 
                        vlines=[], vline_colors=[], vline_styles=[], vline_labels=[],
                        ylim=None, xlim=None, legend=True, title=None, side_title=None, plot_percentages=True,
                        figsize=(12,8), use_seaborn=True, show=True):

        import matplotlib.pyplot as pyplot

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

        if(use_seaborn):
            import seaborn
            seaborn.set_style('ticks')
            seaborn.despine()

        self.plot(ax=ax, plot_S=plot_S, plot_E=plot_E, plot_I=plot_I,plot_R=plot_R, plot_F=plot_F,
                        plot_D_E=plot_D_E, plot_D_I=plot_D_I, combine_D=combine_D,
                        color_S=color_S, color_E=color_E, color_I=color_I, color_R=color_R, color_F=color_F,
                        color_D_E=color_D_E, color_D_I=color_D_I, color_reference=color_reference,
                        dashed_reference_results=dashed_reference_results, dashed_reference_label=dashed_reference_label, 
                        shaded_reference_results=shaded_reference_results, shaded_reference_label=shaded_reference_label, 
                        vlines=vlines, vline_colors=vline_colors, vline_styles=vline_styles, vline_labels=vline_labels,
                        ylim=ylim, xlim=xlim, legend=legend, title=title, side_title=side_title, plot_percentages=plot_percentages)

        if(show):
            pyplot.show()

        return fig, ax
//  [python]
def figure_basic(self, plot_S='line', plot_E='line', plot_I='line',plot_R='line', plot_F='line',
                        plot_D_E='line', plot_D_I='line', combine_D=True,
                        color_S='tab:green', color_E='orange', color_I='crimson', color_R='tab:blue', color_F='black',
                        color_D_E='mediumorchid', color_D_I='mediumorchid', color_reference='#E0E0E0',
                        dashed_reference_results=None, dashed_reference_label='reference', 
                        shaded_reference_results=None, shaded_reference_label='reference', 
                        vlines=[], vline_colors=[], vline_styles=[], vline_labels=[],
                        ylim=None, xlim=None, legend=True, title=None, side_title=None, plot_percentages=True,
                        figsize=(12,8), use_seaborn=True, show=True):

        import matplotlib.pyplot as pyplot

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

        if(use_seaborn):
            import seaborn
            seaborn.set_style('ticks')
            seaborn.utils.despine()

        self.plot(ax=ax, plot_S=plot_S, plot_E=plot_E, plot_I=plot_I,plot_R=plot_R, plot_F=plot_F,
                        plot_D_E=plot_D_E, plot_D_I=plot_D_I, combine_D=combine_D,
                        color_S=color_S, color_E=color_E, color_I=color_I, color_R=color_R, color_F=color_F,
                        color_D_E=color_D_E, color_D_I=color_D_I, color_reference=color_reference,
                        dashed_reference_results=dashed_reference_results, dashed_reference_label=dashed_reference_label, 
                        shaded_reference_results=shaded_reference_results, shaded_reference_label=shaded_reference_label, 
                        vlines=vlines, vline_colors=vline_colors, vline_styles=vline_styles, vline_labels=vline_labels,
                        ylim=ylim, xlim=xlim, legend=legend, title=title, side_title=side_title, plot_percentages=plot_percentages)

        if(show):
            pyplot.show()

        return fig, ax
//  [python]
def _plot_cluster_dist(self):
        plot_data = pd.DataFrame(
            {
                "groups": self.clusters,
                "Doublet Score": self.doublet_scores_obs_,
                "Is Doublet": self.predicted_doublets_,
            }
        )
        fig, ax = plt.subplots(figsize=(6, 2), dpi=300)
        sns.violinplot(data=plot_data, x="groups", y="Doublet Score", linewidth=0, scale="width")
        sns.stripplot(
            data=plot_data,
            x="groups",
            y="Doublet Score",
            s=1,
            hue="Is Doublet",
            palette={True: "red", False: "black"},
        )
        xmin, xmax = ax.get_xlim()
        ax.legend_.remove()
        ax.xaxis.set_tick_params(rotation=90)
        ax.hlines(self.threshold_, xmin, xmax, linestyle="--", linewidth=1, color="gray")
        sns.despine(ax=ax)
//  [python]
def _plot_cluster_dist(self):
        plot_data = pd.DataFrame(
            {
                "groups": self.clusters,
                "Doublet Score": self.doublet_scores_obs_,
                "Is Doublet": self.predicted_doublets_,
            }
        )
        fig, ax = plt.subplots(figsize=(6, 2), dpi=300)
        sns.violinplot(data=plot_data, x="groups", y="Doublet Score", linewidth=0, scale="width")
        sns.stripplot(
            data=plot_data,
            x="groups",
            y="Doublet Score",
            s=1,
            hue="Is Doublet",
            palette={True: "red", False: "black"},
        )
        xmin, xmax = ax.get_xlim()
        ax.legend_.remove()
        ax.xaxis.set_tick_params(rotation=90)
        ax.hlines(self.threshold_, xmin, xmax, linestyle="--", linewidth=1, color="gray")
        sns.utils.despine(ax=ax)
//  [python]
def plot_kdes(subjects, axes):

    ftemp = "correlation_analysis/{}_{}_ifs.pkz"
    for subj, ax in zip(subjects, axes):

        sticks = moss.load_pkl(ftemp.format(subj, "sticks")).corrmat
        rest = moss.load_pkl(ftemp.format(subj, "rest")).corrmat

        triu = np.triu_indices_from(rest, 1)

        sns.kdeplot(sticks[triu], color=".15",
                    label="residual", ax=ax)
        sns.kdeplot(rest[triu], color=".45", dashes=[4, 1],
                    label="resting", ax=ax)

    plt.setp(axes,
             xlim=(-.25, .8), ylim=(0, 17),
             xticks=np.linspace(-.2, .8, 6),
             yticks=[])

    for ax in axes:
        sns.despine(ax=ax, left=True, trim=True)
        plt.setp(ax.get_xticklabels(), size=6)
        plt.setp(ax.get_yticklabels(), size=6)

    axes[0].legend(bbox_to_anchor=(1.2, .8))
    for ax in axes[1:]:
        ax.legend_ = None
//  [python]
def plot_kdes(subjects, axes):

    ftemp = "correlation_analysis/{}_{}_ifs.pkz"
    for subj, ax in zip(subjects, axes):

        sticks = moss.load_pkl(ftemp.format(subj, "sticks")).corrmat
        rest = moss.load_pkl(ftemp.format(subj, "rest")).corrmat

        triu = np.triu_indices_from(rest, 1)

        sns.kdeplot(sticks[triu], color=".15",
                    label="residual", ax=ax)
        sns.kdeplot(rest[triu], color=".45", dashes=[4, 1],
                    label="resting", ax=ax)

    plt.setp(axes,
             xlim=(-.25, .8), ylim=(0, 17),
             xticks=np.linspace(-.2, .8, 6),
             yticks=[])

    for ax in axes:
        sns.utils.despine(ax=ax, left=True, trim=True)
        plt.setp(ax.get_xticklabels(), size=6)
        plt.setp(ax.get_yticklabels(), size=6)

    axes[0].legend(bbox_to_anchor=(1.2, .8))
    for ax in axes[1:]:
        ax.legend_ = None
//  [python]
def figure_infections(self, plot_S=False, plot_E='stacked', plot_I='stacked',plot_R=False, plot_F=False,
                            plot_D_E='stacked', plot_D_I='stacked', combine_D=True,
                            color_S='tab:green', color_E='orange', color_I='crimson', color_R='tab:blue', color_F='black',
                            color_D_E='mediumorchid', color_D_I='mediumorchid', color_reference='#E0E0E0',
                            dashed_reference_results=None, dashed_reference_label='reference', 
                            shaded_reference_results=None, shaded_reference_label='reference', 
                            vlines=[], vline_colors=[], vline_styles=[], vline_labels=[],
                            ylim=None, xlim=None, legend=True, title=None, side_title=None, plot_percentages=True,
                            figsize=(12,8), use_seaborn=True, show=True):

        import matplotlib.pyplot as pyplot

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

        if(use_seaborn):
            import seaborn
            seaborn.set_style('ticks')
            seaborn.despine()

        self.plot(ax=ax, plot_S=plot_S, plot_E=plot_E, plot_I=plot_I,plot_R=plot_R, plot_F=plot_F,
                        plot_D_E=plot_D_E, plot_D_I=plot_D_I, combine_D=combine_D,
                        color_S=color_S, color_E=color_E, color_I=color_I, color_R=color_R, color_F=color_F,
                        color_D_E=color_D_E, color_D_I=color_D_I, color_reference=color_reference,
                        dashed_reference_results=dashed_reference_results, dashed_reference_label=dashed_reference_label, 
                        shaded_reference_results=shaded_reference_results, shaded_reference_label=shaded_reference_label, 
                        vlines=vlines, vline_colors=vline_colors, vline_styles=vline_styles, vline_labels=vline_labels, 
                        ylim=ylim, xlim=xlim, legend=legend, title=title, side_title=side_title, plot_percentages=plot_percentages)

        if(show):
            pyplot.show()

        return fig, ax
//  [python]
def figure_infections(self, plot_S=False, plot_E='stacked', plot_I='stacked',plot_R=False, plot_F=False,
                            plot_D_E='stacked', plot_D_I='stacked', combine_D=True,
                            color_S='tab:green', color_E='orange', color_I='crimson', color_R='tab:blue', color_F='black',
                            color_D_E='mediumorchid', color_D_I='mediumorchid', color_reference='#E0E0E0',
                            dashed_reference_results=None, dashed_reference_label='reference', 
                            shaded_reference_results=None, shaded_reference_label='reference', 
                            vlines=[], vline_colors=[], vline_styles=[], vline_labels=[],
                            ylim=None, xlim=None, legend=True, title=None, side_title=None, plot_percentages=True,
                            figsize=(12,8), use_seaborn=True, show=True):

        import matplotlib.pyplot as pyplot

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

        if(use_seaborn):
            import seaborn
            seaborn.set_style('ticks')
            seaborn.utils.despine()

        self.plot(ax=ax, plot_S=plot_S, plot_E=plot_E, plot_I=plot_I,plot_R=plot_R, plot_F=plot_F,
                        plot_D_E=plot_D_E, plot_D_I=plot_D_I, combine_D=combine_D,
                        color_S=color_S, color_E=color_E, color_I=color_I, color_R=color_R, color_F=color_F,
                        color_D_E=color_D_E, color_D_I=color_D_I, color_reference=color_reference,
                        dashed_reference_results=dashed_reference_results, dashed_reference_label=dashed_reference_label, 
                        shaded_reference_results=shaded_reference_results, shaded_reference_label=shaded_reference_label, 
                        vlines=vlines, vline_colors=vline_colors, vline_styles=vline_styles, vline_labels=vline_labels, 
                        ylim=ylim, xlim=xlim, legend=legend, title=title, side_title=side_title, plot_percentages=plot_percentages)

        if(show):
            pyplot.show()

        return fig, ax
//  [python]
def plot_decision_function(subset_df, filename, title):
    """
    plot and save decision function for classifier

    Arguments:
    subset_df - a pandas dataframe storing prediction and covariate info
    filename - a string holding the filename to save the figure
    title - the title to add to the plot
    """
    sns.set(font_scale=1)
    sns.set_style("white")
    plt.figure(figsize=(3.1, 2.5))
    if subset_df[subset_df.total_status == 1].shape[0] > 0:
        ax = sns.kdeplot(subset_df.ix[subset_df.total_status == 1, :].weight,
                         color='red', label='Deficient', shade=True)
    if subset_df[subset_df.total_status == 0].shape[0] > 0:
        ax = sns.kdeplot(subset_df.ix[subset_df.total_status == 0, :].weight,
                         color='blue', label='Wild-Type', shade=True)
    ax.set(xlabel='Probability', ylabel='Density')
    ax.set_xlim(0, 1.1)
    ax.set_title(title)
    sns.despine()
    plt.axvline(x=0.5, color='k', ls='dashed', linewidth=0.7)
    plt.tight_layout()
    plt.savefig(filename, format='pdf', bbox_inches='tight')
    plt.close()
//  [python]
def plot_decision_function(subset_df, filename, title):
    """
    plot and save decision function for classifier

    Arguments:
    subset_df - a pandas dataframe storing prediction and covariate info
    filename - a string holding the filename to save the figure
    title - the title to add to the plot
    """
    sns.set(font_scale=1)
    sns.set_style("white")
    plt.figure(figsize=(3.1, 2.5))
    if subset_df[subset_df.total_status == 1].shape[0] > 0:
        ax = sns.kdeplot(subset_df.ix[subset_df.total_status == 1, :].weight,
                         color='red', label='Deficient', shade=True)
    if subset_df[subset_df.total_status == 0].shape[0] > 0:
        ax = sns.kdeplot(subset_df.ix[subset_df.total_status == 0, :].weight,
                         color='blue', label='Wild-Type', shade=True)
    ax.set(xlabel='Probability', ylabel='Density')
    ax.set_xlim(0, 1.1)
    ax.set_title(title)
    sns.utils.despine()
    plt.axvline(x=0.5, color='k', ls='dashed', linewidth=0.7)
    plt.tight_layout()
    plt.savefig(filename, format='pdf', bbox_inches='tight')
    plt.close()
//  [python]
def plot():
    df = pd.read_csv("benchmark_feature_aggregation.csv")
    df["n_samples"] = df["n_samples"] / 1000.0 / 1000.0 / 10.0

    sns.set(style="whitegrid")

    fig, ax = plt.subplots(figsize=(12, 6))
    plt.title("Benchmark groupby aggregation (xfeat.helper.aggregate)",
              fontsize=24, pad=24)
    ax = sns.barplot(
        x="n_samples",
        y="process_time_mean",
        hue="method",
        data=df,
        ax=ax,
        palette=["#c7c7c7", "#ce76de"],
    )
    ax.set_ylabel("process time [sec, log]", fontsize=24)
    ax.set_xlabel("num samples [*1e7]", fontsize=24)
    ax.set_yscale("log")
    plt.setp(ax.get_xticklabels(), fontsize=18)
    plt.setp(ax.get_yticklabels(), fontsize=18)
    ax.legend(loc=0, fontsize=20)
    fig.autofmt_xdate(rotation=20)
    fig.patch.set_facecolor("white")
    plt.tight_layout()
    sns.despine(left=True, bottom=True)

    plt.savefig("./_docs/benchmark_groupby_aggregation.png")
//  [python]
def plot():
    df = pd.read_csv("benchmark_feature_aggregation.csv")
    df["n_samples"] = df["n_samples"] / 1000.0 / 1000.0 / 10.0

    sns.set(style="whitegrid")

    fig, ax = plt.subplots(figsize=(12, 6))
    plt.title("Benchmark groupby aggregation (xfeat.helper.aggregate)",
              fontsize=24, pad=24)
    ax = sns.barplot(
        x="n_samples",
        y="process_time_mean",
        hue="method",
        data=df,
        ax=ax,
        palette=["#c7c7c7", "#ce76de"],
    )
    ax.set_ylabel("process time [sec, log]", fontsize=24)
    ax.set_xlabel("num samples [*1e7]", fontsize=24)
    ax.set_yscale("log")
    plt.setp(ax.get_xticklabels(), fontsize=18)
    plt.setp(ax.get_yticklabels(), fontsize=18)
    ax.legend(loc=0, fontsize=20)
    fig.autofmt_xdate(rotation=20)
    fig.patch.set_facecolor("white")
    plt.tight_layout()
    sns.utils.despine(left=True, bottom=True)

    plt.savefig("./_docs/benchmark_groupby_aggregation.png")
//  [python]
def ranking_plot(self, benchmark_snapshot_df, axes=None, bugs=False):
        """Draws ranking plot.

        The fuzzer labels will be in the order of their median coverage.
        """
        self._common_datafame_checks(benchmark_snapshot_df, snapshot=True)

        column_of_interest = 'bugs_covered' if bugs else 'edges_covered'

        fuzzer_order = data_utils.benchmark_rank_by_median(
            benchmark_snapshot_df, key=column_of_interest).index

        axes = sns.barplot(y=column_of_interest,
                           x='fuzzer',
                           data=benchmark_snapshot_df,
                           order=fuzzer_order,
                           estimator=np.median,
                           palette=self._fuzzer_colors,
                           ax=axes)

        axes.set_title(_formatted_title(benchmark_snapshot_df))
        ylabel = f'Reached {"bug" if bugs else "branch"} coverage'
        axes.set(ylabel=ylabel)
        axes.set(xlabel='Fuzzer (highest median coverage on the left)')
        axes.set_xticklabels(axes.get_xticklabels(),
                             rotation=_DEFAULT_LABEL_ROTATION,
                             horizontalalignment='right')

        sns.despine(ax=axes, trim=True)
//  [python]
def ranking_plot(self, benchmark_snapshot_df, axes=None, bugs=False):
        """Draws ranking plot.

        The fuzzer labels will be in the order of their median coverage.
        """
        self._common_datafame_checks(benchmark_snapshot_df, snapshot=True)

        column_of_interest = 'bugs_covered' if bugs else 'edges_covered'

        fuzzer_order = data_utils.benchmark_rank_by_median(
            benchmark_snapshot_df, key=column_of_interest).index

        axes = sns.barplot(y=column_of_interest,
                           x='fuzzer',
                           data=benchmark_snapshot_df,
                           order=fuzzer_order,
                           estimator=np.median,
                           palette=self._fuzzer_colors,
                           ax=axes)

        axes.set_title(_formatted_title(benchmark_snapshot_df))
        ylabel = f'Reached {"bug" if bugs else "branch"} coverage'
        axes.set(ylabel=ylabel)
        axes.set(xlabel='Fuzzer (highest median coverage on the left)')
        axes.set_xticklabels(axes.get_xticklabels(),
                             rotation=_DEFAULT_LABEL_ROTATION,
                             horizontalalignment='right')

        sns.utils.despine(ax=axes, trim=True)
//  [python]
def colorbar(palette, figsize=(10, 1)):
    """
    Plot the values in a color palette as a horizontal array.

    Lightly modified from `seaborn` implementation so that you can plot dense
    colorbars

    Parameters
    ----------
    pal : sequence of matplotlib colors
        Colors, i.e. as returned by seaborn.color_palette()
    """

    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    import seaborn as sns

    n = len(palette)
    fig, ax = plt.subplots(1, 1, figsize=figsize)
    ax.imshow(np.arange(n).reshape(1, n), cmap=ListedColormap(list(palette)),
              interpolation='nearest', aspect='auto')
    ax.set(xticks=np.arange(n) - .5, yticks=[-.5, .5],
           xticklabels=[], yticklabels=[])
    sns.despine(ax=ax, left=True, bottom=True)

    return fig
//  [python]
def colorbar(palette, figsize=(10, 1)):
    """
    Plot the values in a color palette as a horizontal array.

    Lightly modified from `seaborn` implementation so that you can plot dense
    colorbars

    Parameters
    ----------
    pal : sequence of matplotlib colors
        Colors, i.e. as returned by seaborn.color_palette()
    """

    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    import seaborn as sns
    import numpy as np

    n = len(palette)
    fig, ax = plt.subplots(1, 1, figsize=figsize)
    ax.imshow(np.arange(n).reshape(1, n), cmap=ListedColormap(list(palette)),
              interpolation='nearest', aspect='auto')
    ax.set(xticks=np.arange(n) - .5, yticks=[-.5, .5],
           xticklabels=[], yticklabels=[])
    sns.utils.despine(ax=ax, left=True, bottom=True)

    return fig
//  [python]
def unique_coverage_ranking_plot(self,
                                     unique_branch_cov_df_combined,
                                     axes=None):
        """Draws unique_coverage_ranking plot. The fuzzer labels will be in
        the order of their coverage."""

        fuzzer_order = unique_branch_cov_df_combined.sort_values(
            by='unique_branches_covered', ascending=False).fuzzer

        axes = sns.barplot(y='unique_branches_covered',
                           x='fuzzer',
                           data=unique_branch_cov_df_combined,
                           order=fuzzer_order,
                           palette=self._fuzzer_colors,
                           ax=axes)

        for patch in axes.patches:
            axes.annotate(
                format(patch.get_height(), '.0f'),
                (patch.get_x() + patch.get_width() / 2., patch.get_height()),
                ha='center',
                va='center',
                xytext=(0, 10),
                textcoords='offset points')

        sns.barplot(y='aggregated_edges_covered',
                    x='fuzzer',
                    data=unique_branch_cov_df_combined,
                    order=fuzzer_order,
                    facecolor=(1, 1, 1, 0),
                    edgecolor='0.2',
                    ax=axes)

        axes.set(ylabel='Reached unique edge coverage')
        axes.set(xlabel='Fuzzer (highest coverage on the left)')
        axes.set_xticklabels(axes.get_xticklabels(),
                             rotation=_DEFAULT_LABEL_ROTATION,
                             horizontalalignment='right')

        sns.despine(ax=axes, trim=True)
//  [python]
def unique_coverage_ranking_plot(self,
                                     unique_branch_cov_df_combined,
                                     axes=None):
        """Draws unique_coverage_ranking plot. The fuzzer labels will be in
        the order of their coverage."""

        fuzzer_order = unique_branch_cov_df_combined.sort_values(
            by='unique_branches_covered', ascending=False).fuzzer

        axes = sns.barplot(y='unique_branches_covered',
                           x='fuzzer',
                           data=unique_branch_cov_df_combined,
                           order=fuzzer_order,
                           palette=self._fuzzer_colors,
                           ax=axes)

        for patch in axes.patches:
            axes.annotate(
                format(patch.get_height(), '.0f'),
                (patch.get_x() + patch.get_width() / 2., patch.get_height()),
                ha='center',
                va='center',
                xytext=(0, 10),
                textcoords='offset points')

        sns.barplot(y='aggregated_edges_covered',
                    x='fuzzer',
                    data=unique_branch_cov_df_combined,
                    order=fuzzer_order,
                    facecolor=(1, 1, 1, 0),
                    edgecolor='0.2',
                    ax=axes)

        axes.set(ylabel='Reached unique edge coverage')
        axes.set(xlabel='Fuzzer (highest coverage on the left)')
        axes.set_xticklabels(axes.get_xticklabels(),
                             rotation=_DEFAULT_LABEL_ROTATION,
                             horizontalalignment='right')

        sns.utils.despine(ax=axes, trim=True)
//  [python]
def plot(val_curve, system_curves, best_worst, val_label='Val', filename='./Data/Output/ttr_curve_reduced.pdf'):
    fig, ax = plt.subplots(figsize=(34,20))
    lw = 8.0
    x,y = curve_to_coords(val_curve)
    ax = plt.plot(x,y,label=val_label, linewidth=lw)
    system_curves = sorted(system_curves.items(),
                           key=lambda item:item[1][max(item[1])], # Sort by highest value at the max X-value.
                           reverse=True)                          # In decreasing order.
    # plot best
    bx, by = curve_to_coords(best_worst['best'])
    #plt.plot(bx, by, color='gainsboro')
    # plot worst
    wx, wy = curve_to_coords(best_worst['worst'])
    #plt.plot(wx, wy, color='gainsboro')
    plt.fill_between(x, by, wy, color='gainsboro', alpha='0.5')
    
    for name, curve in system_curves:
        x,y = curve_to_coords(curve)
        plt.plot(x,y,label=name, linewidth=lw)
    plt.ylabel('Types')
    plt.xlabel('Tokens')
    sns.despine()
    plt.tick_params(direction='in', length=10, width=4, bottom=True, left=True)
    plt.legend()
    plt.savefig(filename)
    plt.clf()
//  [python]
def plot(val_curve, system_curves, best_worst, val_label='Val', filename='./Data/Output/ttr_curve_reduced.pdf'):
    fig, ax = plt.subplots(figsize=(34,20))
    lw = 8.0
    x,y = curve_to_coords(val_curve)
    ax = plt.plot(x,y,label=val_label, linewidth=lw)
    system_curves = sorted(system_curves.items(),
                           key=lambda item:item[1][max(item[1])], # Sort by highest value at the max X-value.
                           reverse=True)                          # In decreasing order.
    # plot best
    bx, by = curve_to_coords(best_worst['best'])
    #plt.plot(bx, by, color='gainsboro')
    # plot worst
    wx, wy = curve_to_coords(best_worst['worst'])
    #plt.plot(wx, wy, color='gainsboro')
    plt.fill_between(x, by, wy, color='gainsboro', alpha='0.5')
    
    for name, curve in system_curves:
        x,y = curve_to_coords(curve)
        plt.plot(x,y,label=name, linewidth=lw)
    plt.ylabel('Types')
    plt.xlabel('Tokens')
    sns.utils.despine()
    plt.tick_params(direction='in', length=10, width=4, bottom=True, left=True)
    plt.legend()
    plt.savefig(filename)
    plt.clf()
//  [python]
def _make_plot(self, df):
        """
        Build the plot with the dataset in the correct format.

        Parameters
        ----------
        df: pd.DataFrame
            DataFrame with the metrics data.

        Returns
        -------
        ax: matplotlib.axes.Axes
            ax object as returned by matplotlib.
        """
        plt.rcParams["figure.figsize"] = (20, 15)
        plt.rcParams["xtick.labelsize"] = "large"
        plt.rcParams["ytick.labelsize"] = "large"

        ax = sns.barplot(
            y="dataset_name",
            x=self.metric_field,
            data=df.sort_values(["model_name", "dataset_name"]),
            hue="model_name",
        )
        ax.set_xticks(np.linspace(0.0, 1.0, 25))
        plt.grid(True, color="#93a1a1", alpha=0.9, linestyle="--", which="both")
        plt.title(
            "Experiments Results",
            size=22,
            fontdict={
                "fontstyle": "normal",
                "fontfamily": "serif",
                "fontweight": "bold",
            },
        )
        plt.ylabel("Dataset Name", size=18, fontdict={"fontfamily": "serif"})
        plt.xlabel(
            f"{self.metric_field}", size=18, fontdict={"fontfamily": "serif"}
        )
        sns.despine()
        plt.legend(bbox_to_anchor=(0.9, 0.98), loc=3, borderaxespad=0.0)
        return ax
//  [python]
def _make_plot(self, df):
        """
        Build the plot with the dataset in the correct format.

        Parameters
        ----------
        df: pd.DataFrame
            DataFrame with the metrics data.

        Returns
        -------
        ax: matplotlib.axes.Axes
            ax object as returned by matplotlib.
        """
        plt.rcParams["figure.figsize"] = (20, 15)
        plt.rcParams["xtick.labelsize"] = "large"
        plt.rcParams["ytick.labelsize"] = "large"

        ax = sns.barplot(
            y="dataset_name",
            x=self.metric_field,
            data=df.sort_values(["model_name", "dataset_name"]),
            hue="model_name",
        )
        ax.set_xticks(np.linspace(0.0, 1.0, 25))
        plt.grid(True, color="#93a1a1", alpha=0.9, linestyle="--", which="both")
        plt.title(
            "Experiments Results",
            size=22,
            fontdict={
                "fontstyle": "normal",
                "fontfamily": "serif",
                "fontweight": "bold",
            },
        )
        plt.ylabel("Dataset Name", size=18, fontdict={"fontfamily": "serif"})
        plt.xlabel(
            f"{self.metric_field}", size=18, fontdict={"fontfamily": "serif"}
        )
        sns.utils.despine()
        plt.legend(bbox_to_anchor=(0.9, 0.98), loc=3, borderaxespad=0.0)
        return ax
//  [python]
sns.boxplot(x="distance", y="method", data=planets,
            whis="range", palette="vlag")

# Add in points to show each observation
sns.swarmplot(x="distance", y="method", data=planets,
              size=2, color=".3", linewidth=0)

# Tweak the visual presentation
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.despine(trim=True, left=True)
//  [python]
sns.boxplot(x="distance", y="method", data=planets,
            whis="range", palette="vlag")

# Add in points to show each observation
sns.swarmplot(x="distance", y="method", data=planets,
              size=2, color=".3", linewidth=0)

# Tweak the visual presentation
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.utils.despine(trim=True, left=True)