jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def visualize_log(files, keys, grouper=10):
    df_learning = pd.DataFrame()
    
    
    for file in files:
        with open(file, 'r') as f:
            data = json.load(f)
        if 'episode' not in data:
            raise ValueError('Log file "{}" does not contain the "episode" key.'.format(file))
        
        
        df = pd.DataFrame(data)
        df["mean_reward"] = df["episode_reward"] / df["nb_episode_steps"]
        df = df.groupby(df.index // grouper).mean()
        
        df["RL Algorithm"] = algo_names(file)
        df_learning = df_learning.append(df)
        
    
    df_learning = df_learning[df_learning["episode"] < 120]

    f, axs = plt.subplots(1, len(keys))
    for idx, key in enumerate(keys):
        g = sns.lineplot(x="episode", y=key, 
                     style="RL Algorithm", hue="RL Algorithm",
                     dashes=True, markers=True, ci=0,
                     data=df_learning, ax=axs[idx])
        
        ylabel=labels(key)
        g.set(xlabel='Episode', ylabel=ylabel)    
        
        #plt.xticks(np.arange(0, df_learning["episode"].max() + 1, 30));  
        
    plt.tight_layout()
    plt.tight_layout()
    sns.utils.despine(offset=10)
//  [python]
def distributions():

    penguins = sns.load_dataset("penguins").dropna()
    with sns.axes_style("white"):
        g = sns.displot(
            penguins, x="flipper_length_mm", row="island",
            binwidth=4, kde=True, line_kws=dict(linewidth=2), legend=False,
        )
    sns.despine(left=True)
    g.figure.set_size_inches(5, 5)
    return g.figure
//  [python]
def distributions():

    penguins = sns.load_dataset("penguins").dropna()
    with sns.axes_style("white"):
        g = sns.displot(
            penguins, x="flipper_length_mm", row="island",
            binwidth=4, kde=True, line_kws=dict(linewidth=2), legend=False,
        )
    sns.utils.despine(left=True)
    g.figure.set_size_inches(5, 5)
    return g.figure
//  [python]
def categorical():

    penguins = sns.load_dataset("penguins").dropna()
    with sns.axes_style("whitegrid"):
        g = sns.catplot(
            penguins, x="sex", y="body_mass_g", hue="island", col="sex",
            kind="box", whis=np.inf, legend=False, sharex=False,
        )
    sns.despine(left=True)
    g.figure.set_size_inches(5, 5)
    return g.figure
//  [python]
def categorical():

    penguins = sns.load_dataset("penguins").dropna()
    with sns.axes_style("whitegrid"):
        g = sns.catplot(
            penguins, x="sex", y="body_mass_g", hue="island", col="sex",
            kind="box", whis=np.inf, legend=False, sharex=False,
        )
    sns.utils.despine(left=True)
    g.figure.set_size_inches(5, 5)
    return g.figure
//  [python]
def mask_area_hists(self, outdir='./'):
        # TODO: plot against firing rate once traces are repopulated
        with sns.axes_style('ticks'):
            fig, ax = plt.subplots()

        for key in (self.project() * SegmentMethod() & dict(method_name='nmf')).fetch.as_dict:
            area_per_pixel = np.prod((ScanInfo() & key).fetch1['um_width','um_height']) / \
                                np.prod((ScanInfo() & key).fetch1['px_width','px_height'])
            areas = np.array([pxs*area_per_pixel for pxs in map(len, (SegmentMask() & key).fetch['mask_pixels'])])
            ax.hist(areas, bins=20, alpha=.5, lw=0, label="A{animal_id}S{session}:{scan_idx}".format(**key))
        ax.legend()
        sns.despine(fig)
        plt.show()
//  [python]
def mask_area_hists(self, outdir='./'):
        # TODO: plot against firing rate once traces are repopulated
        with sns.axes_style('ticks'):
            fig, ax = plt.subplots()

        for key in (self.project() * SegmentMethod() & dict(method_name='nmf')).fetch.as_dict:
            area_per_pixel = np.prod((ScanInfo() & key).fetch1['um_width','um_height']) / \
                                np.prod((ScanInfo() & key).fetch1['px_width','px_height'])
            areas = np.array([pxs*area_per_pixel for pxs in map(len, (SegmentMask() & key).fetch['mask_pixels'])])
            ax.hist(areas, bins=20, alpha=.5, lw=0, label="A{animal_id}S{session}:{scan_idx}".format(**key))
        ax.legend()
        sns.utils.despine(fig)
        plt.show()
//  [python]
sns.set_theme(style="ticks")

diamonds = sns.load_dataset("diamonds")

f, ax = plt.subplots(figsize=(7, 5))
sns.despine(f)
//  [python]
def aesthetics():

    f = mpl.figure.Figure(figsize=(5, 5))
    for i, style in enumerate(["darkgrid", "white", "ticks", "whitegrid"], 1):
        with sns.axes_style(style):
            ax = f.add_subplot(2, 2, i)
        ax.set(xticks=[0, .25, .5, .75, 1], yticks=[0, .25, .5, .75, 1])
    sns.despine(ax=f.axes[1])
    sns.despine(ax=f.axes[2])
    return f
//  [python]
def aesthetics():

    f = mpl.figure.Figure(figsize=(5, 5))
    for i, style in enumerate(["darkgrid", "white", "ticks", "whitegrid"], 1):
        with sns.axes_style(style):
            ax = f.add_subplot(2, 2, i)
        ax.set(xticks=[0, .25, .5, .75, 1], yticks=[0, .25, .5, .75, 1])
    sns.utils.despine(ax=f.axes[1])
    sns.utils.despine(ax=f.axes[2])
    return f
//  [python]
def plot_roc(directory, ax=None, legend=True):
    roc_path = os.path.join(directory, "roc.csv")

    if not os.path.exists(roc_path):
        print(f"{roc_path} not found, skipping roc plot...")
        return
    if not os.path.getsize(roc_path) > 0:
        print(f"{roc_path} appears to be empty, skipping roc plot...")
        return

    roc = pd.read_csv(roc_path)

    auc_path = os.path.join(directory, "auc.csv")
    auc = pd.read_csv(auc_path)

    save = False
    if ax is None:
        plt.figure(figsize=(6.4, 6.4))
        ax = plt.gca()
        save = True

    labels = list()
    if "type" in auc.columns:
        for tpe in auc.type.unique():
            df = auc[auc.type == tpe]
            auc_mean = float(df.auc)
            auc_std = float(df.std_auc)
            labels.append(
                f"{tpe}\n"
                + r"($\overline{AUC}$"
                + " = {:.2f} ± {:.2f} ".format(auc_mean, auc_std)
                + r"$s$)"
            )
            # labels = [fill(l, 60) for l in labels]
        sns_plot = sns.tsplot(
            x="fpr",
            y="tpr",
            ci=None,
            data=roc,
            condition="type",
            ax=ax,
            # palette=get_palette(roc, "type"),
        )

    else:
        auc_mean = float(auc.auc)
        labels.append(
            "{}\n(AUC = {:.2f})".format(os.path.basename(directory), auc_mean)
        )
        # labels = [fill(l, 60) for l in labels]
        sns_plot = sns.tsplot(x="fpr", y="tpr", ci=None, data=roc, ax=ax)

    sns_plot.set_title("ROC")

    if legend:
        sns_plot.legend(
            labels, title=None, loc="upper center", bbox_to_anchor=(0.5, -0.15)
        )  # loc="lower right")

    sns_plot.set_xlabel("False Positive Rate")
    sns_plot.set_ylabel("True Positive Rate")
    # sns_plot.set_ylim(-0.05, 1.05)
    # sns_plot.set_xlim(-0.05, 1.05)

    if "type" in roc.columns:
        for tpe in roc.type.unique():
            df = roc[roc.type == tpe]
            sns_plot.fill_between(
                df.fpr, df.tpr - df.std_tpr, df.tpr + df.std_tpr, alpha=0.5
            )

    sns_plot.plot([0, 1], [0, 1], "k--")
    if save:
        sns_plot.get_figure().savefig(
            get_output_path(
                directory,
                "roc" + "-" + str(Path(directory).absolute().name).replace(" ", "-"),
            ),
            bbox_inches="tight",
        )
    return True
//  [python]
def plot_roc(directory, ax=None, legend=True):
    roc_path = os.path.join(directory, "roc.csv")

    if not os.path.exists(roc_path):
        print(f"{roc_path} not found, skipping roc plot...")
        return
    if not os.path.getsize(roc_path) > 0:
        print(f"{roc_path} appears to be empty, skipping roc plot...")
        return

    roc = pd.read_csv(roc_path)

    auc_path = os.path.join(directory, "auc.csv")
    auc = pd.read_csv(auc_path)

    save = False
    if ax is None:
        plt.figure(figsize=(6.4, 6.4))
        ax = plt.gca()
        save = True

    labels = list()
    if "type" in auc.columns:
        for tpe in auc.type.unique():
            df = auc[auc.type == tpe]
            auc_mean = float(df.auc)
            auc_std = float(df.std_auc)
            labels.append(
                f"{tpe}\n"
                + r"($\overline{AUC}$"
                + " = {:.2f} ± {:.2f} ".format(auc_mean, auc_std)
                + r"$s$)"
            )
            # labels = [fill(l, 60) for l in labels]
        sns_plot = sns.lineplot(
            x="fpr",
            y="tpr",
            ci=None,
            data=roc,
            hue="type",
            ax=ax,
            # palette=get_palette(roc, "type"),
        )

    else:
        auc_mean = float(auc.auc)
        labels.append(
            "{}\n(AUC = {:.2f})".format(os.path.basename(directory), auc_mean)
        )
        # labels = [fill(l, 60) for l in labels]
        sns_plot = sns.lineplot(x="fpr", y="tpr", ci=None, data=roc, ax=ax)

    sns_plot.set_title("ROC")

    if legend:
        sns_plot.legend(
            labels, title=None, loc="upper center", bbox_to_anchor=(0.5, -0.15)
        )  # loc="lower right")

    sns_plot.set_xlabel("False Positive Rate")
    sns_plot.set_ylabel("True Positive Rate")
    # sns_plot.set_ylim(-0.05, 1.05)
    # sns_plot.set_xlim(-0.05, 1.05)

    if "type" in roc.columns:
        for tpe in roc.type.unique():
            df = roc[roc.type == tpe]
            sns_plot.fill_between(
                df.fpr, df.tpr - df.std_tpr, df.tpr + df.std_tpr, alpha=0.5
            )

    sns_plot.plot([0, 1], [0, 1], "k--")
    if save:
        sns_plot.get_figure().savefig(
            get_output_path(
                directory,
                "roc" + "-" + str(Path(directory).absolute().name).replace(" ", "-"),
            ),
            bbox_inches="tight",
        )
    return True
//  [python]
def properties():

    f = mpl.figure.Figure(figsize=(5, 5))

    x = np.arange(1, 11)
    y = np.zeros_like(x)

    p = so.Plot(x, y)
    ps = 14
    plots = [
        p.add(so.Dot(pointsize=ps), color=map(str, x)),
        p.add(so.Dot(color=".3", pointsize=ps), alpha=x),
        p.add(so.Dot(color=".9", pointsize=ps, edgewidth=2), edgecolor=x),
        p.add(so.Dot(color=".3"), pointsize=x).scale(pointsize=(4, 18)),
        p.add(so.Dot(pointsize=ps, color=".9", edgecolor=".2"), edgewidth=x),
        p.add(so.Dot(pointsize=ps, color=".3"), marker=map(str, x)),
        p.add(so.Dot(pointsize=ps, color=".3", marker="x"), stroke=x),
    ]

    with sns.axes_style("ticks"):
        axs = f.subplots(len(plots))
    for p, ax in zip(plots, axs):
        p.on(ax).plot()
        ax.set(xticks=x, yticks=[], xticklabels=[], ylim=(-.2, .3))
        sns.despine(ax=ax, left=True)
    f.legends = []
    return f
//  [python]
def properties():

    f = mpl.figure.Figure(figsize=(5, 5))

    x = np.arange(1, 11)
    y = np.zeros_like(x)

    p = so.Plot(x, y)
    ps = 14
    plots = [
        p.add(so.Dot(pointsize=ps), color=map(str, x)),
        p.add(so.Dot(color=".3", pointsize=ps), alpha=x),
        p.add(so.Dot(color=".9", pointsize=ps, edgewidth=2), edgecolor=x),
        p.add(so.Dot(color=".3"), pointsize=x).scale(pointsize=(4, 18)),
        p.add(so.Dot(pointsize=ps, color=".9", edgecolor=".2"), edgewidth=x),
        p.add(so.Dot(pointsize=ps, color=".3"), marker=map(str, x)),
        p.add(so.Dot(pointsize=ps, color=".3", marker="x"), stroke=x),
    ]

    with sns.axes_style("ticks"):
        axs = f.subplots(len(plots))
    for p, ax in zip(plots, axs):
        p.on(ax).plot()
        ax.set(xticks=x, yticks=[], xticklabels=[], ylim=(-.2, .3))
        sns.utils.despine(ax=ax, left=True)
    f.legends = []
    return f
//  [python]
def get_figure(self, figsize=(20,1)):

        widths = self.get_relative_widths()

        gs_kw = dict(width_ratios=widths)
        figure = plt.figure(figsize =figsize)
        figure.subplots_adjust(bottom=0.25, top=0.75)


        self.gridspec = gridspec.GridSpec(1, len(widths), figure=figure, wspace=0.1, width_ratios=widths)
        self.axis = {}
        prev_ax = None
        for i,contig in enumerate(self.contigs):
           # i = i + 1 # grid spec indexes from 0

            ax = plt.subplot(self.gridspec[i], sharey=prev_ax)
            self.axis[contig] = ax
            self.reset_axis(contig)
            prev_ax=ax
        sns.despine(left=True)
        figure.canvas.draw()
        return figure
//  [python]
def get_figure(self, figsize=(20,1)):

        widths = self.get_relative_widths()

        gs_kw = dict(width_ratios=widths)
        figure = plt.figure(figsize =figsize)
        figure.subplots_adjust(bottom=0.25, top=0.75)


        self.gridspec = gridspec.GridSpec(1, len(widths), figure=figure, wspace=0.1, width_ratios=widths)
        self.axis = {}
        prev_ax = None
        for i,contig in enumerate(self.contigs):
           # i = i + 1 # grid spec indexes from 0

            ax = plt.subplot(self.gridspec[i], sharey=prev_ax)
            self.axis[contig] = ax
            self.reset_axis(contig)
            prev_ax=ax
        sns.utils.despine(left=True)
        figure.canvas.draw()
        return figure
//  [python]
def plot_results(self, scores, optimal):
        sns.set_style('white')
        sns.set_context('talk')
        plt.subplot(2, 1, 1)
        plt.title(self.label)
        plt.plot(scores)
        plt.ylabel('Average Reward')
        plt.legend(self.agents, loc=4)
        plt.subplot(2, 1, 2)
        plt.plot(optimal * 100)
        plt.ylim(0, 100)
        plt.ylabel('% Optimal Action')
        plt.xlabel('Time Step')
        plt.legend(self.agents, loc=4)
        sns.despine()
        plt.show()
//  [python]
def plot_results(self, scores, optimal):
        sns.set_style('white')
        sns.set_context('talk')
        plt.subplot(2, 1, 1)
        plt.title(self.label)
        plt.plot(scores)
        plt.ylabel('Average Reward')
        plt.legend(self.agents, loc=4)
        plt.subplot(2, 1, 2)
        plt.plot(optimal * 100)
        plt.ylim(0, 100)
        plt.ylabel('% Optimal Action')
        plt.xlabel('Time Step')
        plt.legend(self.agents, loc=4)
        sns.utils.despine()
        plt.show()
//  [python]
def bench_minute_bars(db, n=1):
    print("Running minute_bars benchmark...")

    query = "select * from minute_bars"
    df = {
        "asyncpg_fetch": async_benchmark(asyncpg_fetch(db, query), n=n),
        "asyncpg_copy_csv": async_benchmark(asyncpg_copy_csv(db, query), n=n),
        "psycopg_fetchall": benchmark(psycopg_fetchall(db, query), n=n),
        "psycopg_copy_csv": benchmark(psycopg_copy_csv(db, query), n=n),
        "pgeon_copy": benchmark(pgeon_copy(db, query), n=n),
    }

    df = pd.DataFrame(df)
    df.to_csv("minute_bars.csv", index=False)

    ax = sns.kdeplot(data=df, fill=True)
    ax.get_legend().set_frame_on(False)
    ax.figure.set_size_inches(12, 3)
    ax.xaxis.set_label_text("seconds")
    ax.yaxis.set_visible(False)
    sns.despine(left=True)

    ax.figure.tight_layout()
    ax.figure.savefig("minute_bars.svg")
//  [python]
def bench_minute_bars(db, n=1):
    print("Running minute_bars benchmark...")

    query = "select * from minute_bars"
    df = {
        "asyncpg_fetch": async_benchmark(asyncpg_fetch(db, query), n=n),
        "asyncpg_copy_csv": async_benchmark(asyncpg_copy_csv(db, query), n=n),
        "psycopg_fetchall": benchmark(psycopg_fetchall(db, query), n=n),
        "psycopg_copy_csv": benchmark(psycopg_copy_csv(db, query), n=n),
        "pgeon_copy": benchmark(pgeon_copy(db, query), n=n),
    }

    df = pd.DataFrame(df)
    df.to_csv("minute_bars.csv", index=False)

    ax = sns.kdeplot(data=df, fill=True)
    ax.get_legend().set_frame_on(False)
    ax.figure.set_size_inches(12, 3)
    ax.xaxis.set_label_text("seconds")
    ax.yaxis.set_visible(False)
    sns.utils.despine(left=True)

    ax.figure.tight_layout()
    ax.figure.savefig("minute_bars.svg")
//  [python]
def _plot_profiles(y, ylim, color, path, figsize=(10,3)):
	plt.figure(figsize=figsize)
	plt.plot(y, color=color)

	seaborn.despine()
	plt.xlim(0, y.shape[0])
	plt.xlabel("Relative Coordinate", fontsize=12)
	plt.ylabel("Predicted Signal", fontsize=12)
	plt.ylim(*ylim)
	plt.yticks(fontsize=12)
	plt.savefig(path)
	plt.close()
//  [python]
def _plot_profiles(y, ylim, color, path, figsize=(10,3)):
	plt.figure(figsize=figsize)
	plt.plot(y, color=color)

	seaborn.utils.despine()
	plt.xlim(0, y.shape[0])
	plt.xlabel("Relative Coordinate", fontsize=12)
	plt.ylabel("Predicted Signal", fontsize=12)
	plt.ylim(*ylim)
	plt.yticks(fontsize=12)
	plt.savefig(path)
	plt.close()
//  [python]
def plot_box(df, x, y, hue, tag='eda', directory=None):
    r"""Display a Box Plot.

    Parameters
    ----------
    df : pandas.DataFrame
        The dataframe containing the ``x`` and ``y`` features.
    x : str
        Variable name in ``df`` to display along the x-axis.
    y : str
        Variable name in ``df`` to display along the y-axis.
    hue : str
        Variable name to be used as hue, i.e., another data dimension.
    tag : str
        Unique identifier for the plot.
    directory : str, optional
        The full specification of the plot location.

    Returns
    -------
    None : None.

    References
    ----------

    http://seaborn.pydata.org/generated/seaborn.boxplot.html

    """

    logger.info("Generating Box Plot")

    # Generate the box plot

    box_plot = sns.boxplot(x=x, y=y, hue=hue, data=df)
    sns.despine(offset=10, trim=True)
    box_fig = box_plot.get_figure()

    # Save the plot
    write_plot('seaborn', box_fig, 'box_plot', tag, directory)
//  [python]
def plot_box(df, x, y, hue, tag='eda', directory=None):
    r"""Display a Box Plot.

    Parameters
    ----------
    df : pandas.DataFrame
        The dataframe containing the ``x`` and ``y`` features.
    x : str
        Variable name in ``df`` to display along the x-axis.
    y : str
        Variable name in ``df`` to display along the y-axis.
    hue : str
        Variable name to be used as hue, i.e., another data dimension.
    tag : str
        Unique identifier for the plot.
    directory : str, optional
        The full specification of the plot location.

    Returns
    -------
    None : None.

    References
    ----------

    http://seaborn.pydata.org/generated/seaborn.boxplot.html

    """

    logger.info("Generating Box Plot")

    # Generate the box plot

    box_plot = sns.boxplot(x=x, y=y, hue=hue, data=df)
    sns.utils.despine(offset=10, trim=True)
    box_fig = box_plot.get_figure()

    # Save the plot
    write_plot('seaborn', box_fig, 'box_plot', tag, directory)
//  [python]
def plot_data(age,income,sex):
    plt.figure(figsize=(7.5,2.5))
    sns.set_theme(style="white", palette="pastel", font_scale=1.5, font="DejaVu Sans")
    ageranges = np.digitize(age, bins=[0,20,30,40,50])
    sex = np.array(['female' if s==2 else 'male' for s in sex])
    sns.boxplot(x=ageranges, y=income, hue=sex, showfliers=False)
    plt.gca().set_xticklabels(['0-20','20-30','30-40','40-50','50+'])
    plt.ylabel('income ($)')
    sns.despine(top=True, right=True)
    plt.tight_layout()
    os.makedirs("./ols-plots", exist_ok=True)
    plt.savefig("./ols-plots/raw_data.pdf")
//  [python]
def plot_data(age,income,sex):
    plt.figure(figsize=(7.5,2.5))
    sns.set_theme(style="white", palette="pastel", font_scale=1.5, font="DejaVu Sans")
    ageranges = np.digitize(age, bins=[0,20,30,40,50])
    sex = np.array(['female' if s==2 else 'male' for s in sex])
    sns.boxplot(x=ageranges, y=income, hue=sex, showfliers=False)
    plt.gca().set_xticklabels(['0-20','20-30','30-40','40-50','50+'])
    plt.ylabel('income ($)')
    sns.utils.despine(top=True, right=True)
    plt.tight_layout()
    os.makedirs("./ols-plots", exist_ok=True)
    plt.savefig("./ols-plots/raw_data.pdf")
//  [python]
def _plot_counts(y_before, y_after, xlim, ylim, color, path, figsize=(10,3)):
	zmax = max(xlim[1], ylim[1])
	zmin = min(xlim[0], ylim[0])

	plt.figure(figsize=figsize)
	plt.plot([zmin, zmax], [zmin, zmax], color='0.5')
	plt.scatter(y_before, y_after, color=color, s=5)

	seaborn.despine()
	plt.xlabel("Pred Counts Before", fontsize=12)
	plt.ylabel("Pred Counts After", fontsize=12)
	plt.xlim(*xlim)
	plt.ylim(*ylim)
	plt.yticks(fontsize=12)
	plt.savefig(path)
	plt.close()
//  [python]
def _plot_counts(y_before, y_after, xlim, ylim, color, path, figsize=(10,3)):
	zmax = max(xlim[1], ylim[1])
	zmin = min(xlim[0], ylim[0])

	plt.figure(figsize=figsize)
	plt.plot([zmin, zmax], [zmin, zmax], color='0.5')
	plt.scatter(y_before, y_after, color=color, s=5)

	seaborn.utils.despine()
	plt.xlabel("Pred Counts Before", fontsize=12)
	plt.ylabel("Pred Counts After", fontsize=12)
	plt.xlim(*xlim)
	plt.ylim(*ylim)
	plt.yticks(fontsize=12)
	plt.savefig(path)
	plt.close()
//  [python]
def plot_label_distributions(data, num_labels=None, title=None, fig_size=(10, 10), font_size=15, xtick_rotation=0):
    # Reshape dataframe for plotting
    data_reshaped = data.drop(['Dialogue Act', 'Count', '%', 'Train Count', 'Test Count', 'Val Count'], axis=1)
    if num_labels:
        data_reshaped = data_reshaped.head(num_labels)
    data_reshaped = data_reshaped.melt(id_vars='Labels', var_name='set', value_name='percentage')

    # Create figure and barchart
    fig = plt.figure(figsize=fig_size)
    sns.barplot(x='Labels', y='percentage', hue='set', data=data_reshaped)
    sns.despine(left=True, bottom=True)

    # Set legend and axis labels
    plt.legend(ncol=1, loc="upper right", frameon=True)
    plt.ylabel('%', fontsize=font_size)
    plt.xlabel('Labels', fontsize=font_size)
    plt.xticks(rotation=xtick_rotation)
    if title:
        plt.title(title, fontsize=font_size)
    plt.tight_layout()
    return fig
//  [python]
def plot_label_distributions(data, num_labels=None, title=None, fig_size=(10, 10), font_size=15, xtick_rotation=0):
    # Reshape dataframe for plotting
    data_reshaped = data.drop(['Dialogue Act', 'Count', '%', 'Train Count', 'Test Count', 'Val Count'], axis=1)
    if num_labels:
        data_reshaped = data_reshaped.head(num_labels)
    data_reshaped = data_reshaped.melt(id_vars='Labels', var_name='set', value_name='percentage')

    # Create figure and barchart
    fig = plt.figure(figsize=fig_size)
    sns.barplot(x='Labels', y='percentage', hue='set', data=data_reshaped)
    sns.utils.despine(left=True, bottom=True)

    # Set legend and axis labels
    plt.legend(ncol=1, loc="upper right", frameon=True)
    plt.ylabel('%', fontsize=font_size)
    plt.xlabel('Labels', fontsize=font_size)
    plt.xticks(rotation=xtick_rotation)
    if title:
        plt.title(title, fontsize=font_size)
    plt.tight_layout()
    return fig
//  [python]
def remove_junk(axis):
    sns.despine(ax=axis, left=True)
    axis.xaxis.grid(False)
//  [python]
def remove_junk(axis):
    sns.utils.despine(ax=axis, left=True)
    axis.xaxis.grid(False)
//  [python]
def make_histograms(df, axs):
    # Width figure
    kde0 = sns.kdeplot(df[(df["coefficient"]=="age") & (df["estimator"] != "imputed")], ax=axs[0], x="width", hue="estimator", hue_order=["prediction-powered", "classical"], fill=True, clip=(0,None), cut=0)
    axs[0].set_ylabel("")
    axs[0].set_xlabel("width (age coeff, $/yr)")
    axs[0].set_yticks([])
    axs[0].set_yticklabels([])
    kde0.get_legend().remove()
    sns.despine(ax=axs[0],top=True,right=True,left=True)

    kde1 = sns.kdeplot(df[(df["coefficient"]=="age") & (df["estimator"] != "imputed")], ax=axs[1], x="width", hue="estimator", hue_order=["prediction-powered", "classical"], fill=True, clip=(0,None), cut=0)
    axs[1].set_ylabel("")
    axs[1].set_xlabel("width (sex coeff, $)")
    axs[1].set_yticks([])
    axs[1].set_yticklabels([])
    kde1.get_legend().remove()
    sns.despine(ax=axs[1],top=True,right=True,left=True)

    cvg_classical_age = (df[(df["estimator"]=="classical") & (df["coefficient"]=="age")]["covered"]).astype(int).mean()
    cvg_classical_sex = (df[(df["estimator"]=="classical") & (df["coefficient"]=="sex")]["covered"]).astype(int).mean()
    cvg_predictionpowered_age = (df[(df["estimator"]=="prediction-powered") & (df["coefficient"]=="age")]["covered"]).astype(int).mean()
    cvg_predictionpowered_sex = (df[(df["estimator"]=="prediction-powered") & (df["coefficient"]=="sex")]["covered"]).astype(int).mean()
//  [python]
def make_histograms(df, axs):
    # Width figure
    kde0 = sns.kdeplot(df[(df["coefficient"]=="age") & (df["estimator"] != "imputed")], ax=axs[0], x="width", hue="estimator", hue_order=["prediction-powered", "classical"], fill=True, clip=(0,None), cut=0)
    axs[0].set_ylabel("")
    axs[0].set_xlabel("width (age coeff, $/yr)")
    axs[0].set_yticks([])
    axs[0].set_yticklabels([])
    kde0.get_legend().remove()
    sns.utils.despine(ax=axs[0],top=True,right=True,left=True)

    kde1 = sns.kdeplot(df[(df["coefficient"]=="age") & (df["estimator"] != "imputed")], ax=axs[1], x="width", hue="estimator", hue_order=["prediction-powered", "classical"], fill=True, clip=(0,None), cut=0)
    axs[1].set_ylabel("")
    axs[1].set_xlabel("width (sex coeff, $)")
    axs[1].set_yticks([])
    axs[1].set_yticklabels([])
    kde1.get_legend().remove()
    sns.utils.despine(ax=axs[1],top=True,right=True,left=True)

    cvg_classical_age = (df[(df["estimator"]=="classical") & (df["coefficient"]=="age")]["covered"]).astype(int).mean()
    cvg_classical_sex = (df[(df["estimator"]=="classical") & (df["coefficient"]=="sex")]["covered"]).astype(int).mean()
    cvg_predictionpowered_age = (df[(df["estimator"]=="prediction-powered") & (df["coefficient"]=="age")]["covered"]).astype(int).mean()
    cvg_predictionpowered_sex = (df[(df["estimator"]=="prediction-powered") & (df["coefficient"]=="sex")]["covered"]).astype(int).mean()
//  [python]
def hist(model, data, keys=None):
    df = data.as_dataframe(model.responses.keys() if keys is None else _combine_keys(keys))
    keys = model.responses.keys()
    
    f, axes = plt.subplots(1, len(keys))
    sns.despine(left=True)
    
    for i, k in enumerate(keys):
        sns.distplot(df[k], kde=False, ax=axes[i])
        
    plt.setp(axes, yticks=[])
    plt.tight_layout()
//  [python]
def hist(model, data, keys=None):
    df = data.as_dataframe(model.responses.keys() if keys is None else _combine_keys(keys))
    keys = model.responses.keys()
    
    f, axes = plt.subplots(1, len(keys))
    sns.utils.despine(left=True)
    
    for i, k in enumerate(keys):
        sns.distplot(df[k], kde=False, ax=axes[i])
        
    plt.setp(axes, yticks=[])
    plt.tight_layout()
//  [python]
def viz_setup():
    # This sets reasonable defaults for font size for
    # a figure that will go in a paper
    sns.set_context("paper")    
  
    # Set the font to be serif, rather than sans
    custom_rc={
        'grid.linestyle' : '--',
        'font.family': ['sans-serif'],
        'font.sans-serif': [
            'DejaVu Serif',
            'sans-serif',
            'Arial'],
        'axes.grid':True,
    }

    # Enable ticks
    sns.set(
        style='ticks',
        font_scale=5,
        color_codes=False,
        rc=custom_rc, 
    )

    #Control borders around chart.
    # sns.despine()
    sns.despine(offset=10, trim=True)
//  [python]
def viz_setup():
    # This sets reasonable defaults for font size for
    # a figure that will go in a paper
    sns.set_context("paper")    
  
    # Set the font to be serif, rather than sans
    custom_rc={
        'grid.linestyle' : '--',
        'font.family': ['sans-serif'],
        'font.sans-serif': [
            'DejaVu Serif',
            'sans-serif',
            'Arial'],
        'axes.grid':True,
    }

    # Enable ticks
    sns.set(
        style='ticks',
        font_scale=5,
        color_codes=False,
        rc=custom_rc, 
    )

    #Control borders around chart.
    # sns.despine()
    sns.utils.despine(offset=10, trim=True)
//  [python]
def update_ax(ax, title=None, xlabel=None, ylabel=None, legend_loc='best', ticks=True, ticks_fs=10, label_fs=12, legend_fs=12, title_fs=14, hide_xlabels=False, hide_ylabels=False, despine=True):
    if title: ax.set_title(title, fontsize=title_fs)
    if xlabel: ax.set_xlabel(xlabel, fontsize=label_fs)
    if ylabel: ax.set_ylabel(ylabel, fontsize=label_fs)
    if legend_loc: ax.legend(loc=legend_loc, fontsize=legend_fs)
    if despine: sns.despine(ax=ax)

    if ticks:
        # ax.minorticks_on()
        ax.tick_params(direction='in', length=6, width=2, colors='k', which='major', top=False, right=False)
        ax.tick_params(direction='in', length=4, width=1, colors='k', which='minor', top=False, right=False)
        ax.tick_params(labelsize=ticks_fs)

    if hide_xlabels: ax.set_xticks([])
    if hide_ylabels: ax.set_yticks([])
    return ax
//  [python]
def update_ax(ax, title=None, xlabel=None, ylabel=None, legend_loc='best', ticks=True, ticks_fs=10, label_fs=12, legend_fs=12, title_fs=14, hide_xlabels=False, hide_ylabels=False, despine=True):
    if title: ax.set_title(title, fontsize=title_fs)
    if xlabel: ax.set_xlabel(xlabel, fontsize=label_fs)
    if ylabel: ax.set_ylabel(ylabel, fontsize=label_fs)
    if legend_loc: ax.legend(loc=legend_loc, fontsize=legend_fs)
    if despine: sns.utils.despine(ax=ax)

    if ticks:
        # ax.minorticks_on()
        ax.tick_params(direction='in', length=6, width=2, colors='k', which='major', top=False, right=False)
        ax.tick_params(direction='in', length=4, width=1, colors='k', which='minor', top=False, right=False)
        ax.tick_params(labelsize=ticks_fs)

    if hide_xlabels: ax.set_xticks([])
    if hide_ylabels: ax.set_yticks([])
    return ax
//  [python]
def bar(self, counts, phenotype_to_color=None, ax=None, percentages=True):
        """Draw barplots grouped by modality of modality percentage per group

        Parameters
        ----------


        Returns
        -------


        Raises
        ------

        """
        if percentages:
            counts = 100 * (counts.T / counts.T.sum()).T

        # with sns.set(style='whitegrid'):
        if ax is None:
            ax = plt.gca()

        full_width = 0.8
        width = full_width / counts.shape[0]
        for i, (group, series) in enumerate(counts.iterrows()):
            left = np.arange(len(self.modality_order)) + i * width
            height = [series[i] if i in series else 0
                      for i in self.modality_order]
            color = phenotype_to_color[group]
            ax.bar(left, height, width=width, color=color, label=group,
                   linewidth=.5, edgecolor='k')
        ylabel = 'Percentage of events' if percentages else 'Number of events'
        ax.set_ylabel(ylabel)
        ax.set_xticks(np.arange(len(self.modality_order)) + full_width / 2)
        ax.set_xticklabels(self.modality_order)
        ax.set_xlabel('Splicing modality')
        ax.set_xlim(0, len(self.modality_order))
        ax.legend(loc='best')
        ax.grid(axis='y', linestyle='-', linewidth=0.5)
        sns.despine()
//  [python]
def bar(self, counts, phenotype_to_color=None, ax=None, percentages=True):
        """Draw barplots grouped by modality of modality percentage per group

        Parameters
        ----------


        Returns
        -------


        Raises
        ------

        """
        if percentages:
            counts = 100 * (counts.T / counts.T.sum()).T

        # with sns.set(style='whitegrid'):
        if ax is None:
            ax = plt.gca()

        full_width = 0.8
        width = full_width / counts.shape[0]
        for i, (group, series) in enumerate(counts.iterrows()):
            left = np.arange(len(self.modality_order)) + i * width
            height = [series[i] if i in series else 0
                      for i in self.modality_order]
            color = phenotype_to_color[group]
            ax.bar(left, height, width=width, color=color, label=group,
                   linewidth=.5, edgecolor='k')
        ylabel = 'Percentage of events' if percentages else 'Number of events'
        ax.set_ylabel(ylabel)
        ax.set_xticks(np.arange(len(self.modality_order)) + full_width / 2)
        ax.set_xticklabels(self.modality_order)
        ax.set_xlabel('Splicing modality')
        ax.set_xlim(0, len(self.modality_order))
        ax.legend(loc='best')
        ax.grid(axis='y', linestyle='-', linewidth=0.5)
        sns.utils.despine()
//  [python]
def hide_axis(ax):
    """
    Hide the axis bar, ticks and tick labels on all sides.

    :param ax: matplotlib Axes instance
    """
    sns.despine(ax=ax, top=True, left=True, bottom=True, right=True)
    try:
        plt.setp(ax.get_xticklabels(), visible=False)
    except IndexError:
        pass
    try:
        plt.setp(ax.get_yticklabels(), visible=False)
    except IndexError:
        pass
    try:
        plt.setp(ax.get_xticklines(), visible=False)
    except IndexError:
        pass
    try:
        plt.setp(ax.get_yticklines(), visible=False)
    except IndexError:
        pass
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.xaxis.offsetText.set_visible(False)
    ax.yaxis.offsetText.set_visible(False)
//  [python]
def hide_axis(ax):
    """
    Hide the axis bar, ticks and tick labels on all sides.

    :param ax: matplotlib Axes instance
    """
    sns.utils.despine(ax=ax, top=True, left=True, bottom=True, right=True)
    try:
        plt.setp(ax.get_xticklabels(), visible=False)
    except IndexError:
        pass
    try:
        plt.setp(ax.get_yticklabels(), visible=False)
    except IndexError:
        pass
    try:
        plt.setp(ax.get_xticklines(), visible=False)
    except IndexError:
        pass
    try:
        plt.setp(ax.get_yticklines(), visible=False)
    except IndexError:
        pass
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.xaxis.offsetText.set_visible(False)
    ax.yaxis.offsetText.set_visible(False)
//  [python]
def plot_prediction_curves(subjects, axes, exp):

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

        res = moss.load_pkl(res_ftemp.format(subj, exp))
        x = res.steps

        norm = res.null.mean()
        real = res.real / norm
        pint = res.pint / norm

        ax.plot(x, real, "o-", color=".15",
                ms=2.5, clip_on=False)
        ax.fill_between(x, *pint, color=".4", alpha=.3)

        cross_x, cross_y = res.intersect
        cross_y /= norm

        ax.plot([cross_x, cross_x], [0, cross_y],
                lw=.8, dashes=[3, 1], color=".5", zorder=0)

        ax.set(xlim=(0, 40), ylim=(0, 2),
               xticks=np.linspace(0, 40, 5),
               yticks=[0, 1, 2],
               yticklabels=[0, 1, 2])

        sns.despine(ax=ax)

    ylabel = "Normalized error"
    plt.setp(axes[1:7], yticklabels=[])
    axes[0].set(ylabel=ylabel)

    if exp == "dots":
        plt.setp(axes[8:], yticklabels=[])
        plt.setp(axes[:7], xticklabels=[])
        axes[7].set_ylabel(ylabel)
//  [python]
def plot_prediction_curves(subjects, axes, exp):

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

        res = moss.load_pkl(res_ftemp.format(subj, exp))
        x = res.steps

        norm = res.null.mean()
        real = res.real / norm
        pint = res.pint / norm

        ax.plot(x, real, "o-", color=".15",
                ms=2.5, clip_on=False)
        ax.fill_between(x, *pint, color=".4", alpha=.3)

        cross_x, cross_y = res.intersect
        cross_y /= norm

        ax.plot([cross_x, cross_x], [0, cross_y],
                lw=.8, dashes=[3, 1], color=".5", zorder=0)

        ax.set(xlim=(0, 40), ylim=(0, 2),
               xticks=np.linspace(0, 40, 5),
               yticks=[0, 1, 2],
               yticklabels=[0, 1, 2])

        sns.utils.despine(ax=ax)

    ylabel = "Normalized error"
    plt.setp(axes[1:7], yticklabels=[])
    axes[0].set(ylabel=ylabel)

    if exp == "dots":
        plt.setp(axes[8:], yticklabels=[])
        plt.setp(axes[:7], xticklabels=[])
        axes[7].set_ylabel(ylabel)
//  [python]
def _plot(self, region):
        if self.cax is None:
            self.cax = append_axes(self.ax, 'right', 0.3, 0.05)
        # Check if ax has already been split
        if self.parent_ax is not self.ax:
            self.parent_ax = self.ax
            self.top_ax, self.bottom_ax = self._add_split_ax(self.ax, self.gap, sharex=True)
            sns.despine(ax=self.ax, top=True, left=True, bottom=False, right=True)
            self.ax.yaxis.set_major_locator(NullLocator())
            self.ax.yaxis.set_minor_locator(NullLocator())
        if self.parent_cax is not self.cax:
            self.parent_cax = self.cax
            self.top_plot.cax, self.bottom_plot.cax = self._add_split_ax(self.cax, self.cax_gap)
            self.cax.set_visible(False)
        self.top_plot.ax = self.top_ax
        self.top_plot.plot(region)
        self.bottom_plot.ax = self.bottom_ax
        self.bottom_plot.plot(region)
        self.bottom_ax.invert_yaxis()
        hide_axis(self.top_ax)
        hide_axis(self.bottom_ax)
//  [python]
def _plot(self, region):
        if self.cax is None:
            self.cax = append_axes(self.ax, 'right', 0.3, 0.05)
        # Check if ax has already been split
        if self.parent_ax is not self.ax:
            self.parent_ax = self.ax
            self.top_ax, self.bottom_ax = self._add_split_ax(self.ax, self.gap, sharex=True)
            sns.utils.despine(ax=self.ax, top=True, left=True, bottom=False, right=True)
            self.ax.yaxis.set_major_locator(NullLocator())
            self.ax.yaxis.set_minor_locator(NullLocator())
        if self.parent_cax is not self.cax:
            self.parent_cax = self.cax
            self.top_plot.cax, self.bottom_plot.cax = self._add_split_ax(self.cax, self.cax_gap)
            self.cax.set_visible(False)
        self.top_plot.ax = self.top_ax
        self.top_plot.plot(region)
        self.bottom_plot.ax = self.bottom_ax
        self.bottom_plot.plot(region)
        self.bottom_ax.invert_yaxis()
        hide_axis(self.top_ax)
        hide_axis(self.bottom_ax)
//  [python]
def _plot(self, region):
        for i, x, y in self._line_values(region):
            l = self.ax.plot(x, y, label=self.names[i] if self.names else "",
                             **self.plot_kwargs)[0]
            self.lines.append(l)
            if self.fill:
                self.ax.fill_between(x, [0] * len(y), y, color=l.get_color())
        if self.names:
            self.add_legend()
        self.remove_colorbar_ax()
        sns.despine(ax=self.ax, top=True, right=True)
//  [python]
def _plot(self, region):
        for i, x, y in self._line_values(region):
            l = self.ax.plot(x, y, label=self.names[i] if self.names else "",
                             **self.plot_kwargs)[0]
            self.lines.append(l)
            if self.fill:
                self.ax.fill_between(x, [0] * len(y), y, color=l.get_color())
        if self.names:
            self.add_legend()
        self.remove_colorbar_ax()
        sns.utils.despine(ax=self.ax, top=True, right=True)
//  [python]
def _plot(self, region):
        limits = [999999999999999, 0]

        for i, x, y in self._line_values(region):
            limits[0] = min(limits[0], x[0])
            limits[1] = max(limits[1], x[-1])
            kwargs = self.plot_kwargs.copy()
            kwargs.setdefault('color', next(self.colors))
            kwargs.setdefault('label', self.labels[i] if self.labels else "")
            l = self.ax.plot(x, y, **kwargs)[0]

            self.lines.append(l)
            if self.fill:
                f = self.ax.fill_between(x, [0] * len(y), y, color=l.get_color(), alpha=l.get_alpha())
                self.fills.append(f)
        if self.labels is not None:
            if self.show_legend or (self.show_legend is None and len(self.labels) > 1):
                self.ax.legend(self.lines, self.labels, loc=self.legend_location)

        self.remove_colorbar_ax()
        sns.despine(ax=self.ax, top=True, right=True)
        
        if region.start is not None and region.end is not None:
            self.ax.set_xlim([region.start, region.end])
//  [python]
def _plot(self, region):
        limits = [999999999999999, 0]

        for i, x, y in self._line_values(region):
            limits[0] = min(limits[0], x[0])
            limits[1] = max(limits[1], x[-1])
            kwargs = self.plot_kwargs.copy()
            kwargs.setdefault('color', next(self.colors))
            kwargs.setdefault('label', self.labels[i] if self.labels else "")
            l = self.ax.plot(x, y, **kwargs)[0]

            self.lines.append(l)
            if self.fill:
                f = self.ax.fill_between(x, [0] * len(y), y, color=l.get_color(), alpha=l.get_alpha())
                self.fills.append(f)
        if self.labels is not None:
            if self.show_legend or (self.show_legend is None and len(self.labels) > 1):
                self.ax.legend(self.lines, self.labels, loc=self.legend_location)

        self.remove_colorbar_ax()
        sns.utils.despine(ax=self.ax, top=True, right=True)
        
        if region.start is not None and region.end is not None:
            self.ax.set_xlim([region.start, region.end])
//  [python]
def _plot(self, region):
        self._draw_lines(region)

        self.remove_colorbar_ax()
        sns.despine(ax=self.ax, top=True, right=True)
//  [python]
def _plot(self, region):
        self._draw_lines(region)

        self.remove_colorbar_ax()
        sns.utils.despine(ax=self.ax, top=True, right=True)
//  [python]
def _plot(self, region):
        bars = []
        for i, (x, w, h, c) in enumerate(self._bar_values(region)):
            kwargs = self.plot_kwargs.copy()
            kwargs.setdefault('color', c)
            kwargs.setdefault('align', 'edge')
            kwargs.setdefault('label', self.labels[i] if self.labels else "")
            kwargs.setdefault('alpha', self.alpha)

            b = self.ax.bar(x, h, w, **kwargs)
            if b is not None and len(b) > 0:
                bars.append(b[0])

        if self.labels is not None:
            if self.show_legend or (self.show_legend is None and len(self.labels) > 1):
                self.ax.legend(bars, self.labels, loc=self.legend_location)
        self.remove_colorbar_ax()
        sns.despine(ax=self.ax, top=True, right=True)
        
        if region.start is not None and region.end is not None:
            self.ax.set_xlim([region.start, region.end])
//  [python]
def _plot(self, region):
        bars = []
        for i, (x, w, h, c) in enumerate(self._bar_values(region)):
            kwargs = self.plot_kwargs.copy()
            kwargs.setdefault('color', c)
            kwargs.setdefault('align', 'edge')
            kwargs.setdefault('label', self.labels[i] if self.labels else "")
            kwargs.setdefault('alpha', self.alpha)

            b = self.ax.bar(x, h, w, **kwargs)
            if b is not None and len(b) > 0:
                bars.append(b[0])

        if self.labels is not None:
            if self.show_legend or (self.show_legend is None and len(self.labels) > 1):
                self.ax.legend(bars, self.labels, loc=self.legend_location)
        self.remove_colorbar_ax()
        sns.utils.despine(ax=self.ax, top=True, right=True)
        
        if region.start is not None and region.end is not None:
            self.ax.set_xlim([region.start, region.end])
//  [python]
def _plot(self, region):
        self._plot_genes(region=region)

        def drag_pan(self, button, key, x, y):
            mpl.axes.Axes.drag_pan(self, button, 'x', x, y)  # pretend key=='x'

        self.ax.drag_pan = types.MethodType(drag_pan, self.ax)
        self.ax.get_yaxis().set_visible(False)
        sns.despine(ax=self.ax, top=True, right=True, left=True)
        self.remove_colorbar_ax()
//  [python]
def _plot(self, region):
        self._plot_genes(region=region)

        def drag_pan(self, button, key, x, y):
            mpl.axes.Axes.drag_pan(self, button, 'x', x, y)  # pretend key=='x'

        self.ax.drag_pan = types.MethodType(drag_pan, self.ax)
        self.ax.get_yaxis().set_visible(False)
        sns.utils.despine(ax=self.ax, top=True, right=True, left=True)
        self.remove_colorbar_ax()
//  [python]
def _plot(self, region):
        interval = region_to_pbt_interval(region)
        genes = self.bedtool.all_hits(interval)
        trans = self.ax.get_xaxis_transform()
        pos = {k: i/(1 + self._n_tracks)
               for i, k in (enumerate(self.feature_types) if self.feature_types else [(0, "")])}
        stroke_length = max(0.03, 1/self._n_tracks - .05)
        for k, p in pos.items():
            self.ax.text(0, p, k, transform=self.ax.transAxes, ha="left", size=5)
        for g in genes:
            feature_type = g[2] if self.feature_types else ""
            if self.feature_types and feature_type not in self.feature_types:
                continue
            label = get_region_field(g, self.label_field, return_default="") if self.label_field else ""
            gene_patch = patches.Rectangle(
                (g.start, pos[feature_type]),
                width=abs(g.end - g.start), height=stroke_length,
                transform=trans, color=self.color
            )
            self.ax.add_patch(gene_patch)
            label_x = .5*(max(region.start, g.start) + min(region.end, g.end))
            self.ax.text(label_x, pos[feature_type] + stroke_length + .05,
                         label if not self.label_func else self.label_func(g),
                         transform=trans, ha="center", size="small")

        sns.despine(ax=self.ax, top=True, left=True, right=True)
        self.ax.yaxis.set_major_locator(NullLocator())
        self.remove_colorbar_ax()
//  [python]
def _plot(self, region):
        interval = region_to_pbt_interval(region)
        genes = self.bedtool.all_hits(interval)
        trans = self.ax.get_xaxis_transform()
        pos = {k: i/(1 + self._n_tracks)
               for i, k in (enumerate(self.feature_types) if self.feature_types else [(0, "")])}
        stroke_length = max(0.03, 1/self._n_tracks - .05)
        for k, p in pos.items():
            self.ax.text(0, p, k, transform=self.ax.transAxes, ha="left", size=5)
        for g in genes:
            feature_type = g[2] if self.feature_types else ""
            if self.feature_types and feature_type not in self.feature_types:
                continue
            label = get_region_field(g, self.label_field, return_default="") if self.label_field else ""
            gene_patch = patches.Rectangle(
                (g.start, pos[feature_type]),
                width=abs(g.end - g.start), height=stroke_length,
                transform=trans, color=self.color
            )
            self.ax.add_patch(gene_patch)
            label_x = .5*(max(region.start, g.start) + min(region.end, g.end))
            self.ax.text(label_x, pos[feature_type] + stroke_length + .05,
                         label if not self.label_func else self.label_func(g),
                         transform=trans, ha="center", size="small")

        sns.utils.despine(ax=self.ax, top=True, left=True, right=True)
        self.ax.yaxis.set_major_locator(NullLocator())
        self.remove_colorbar_ax()
//  [python]
def plot_ax(ax, data, xlabel):
    palette = ["#5847AD", "#F7B449"]
    kws = dict(orient="v", errorbar="sd", palette=palette, width=0.6)
    sns.barplot(data=data, ax=ax, **kws)
    data.melt().pipe((sns.scatterplot, "data"), y="value", x="variable", ax=ax,
                     zorder=100, color="grey", alpha=0.5)
    ax.get_xticklabels()[0].set_fontweight("bold")
    ax.tick_params(axis="x", rotation=45)
    ax.tick_params(bottom=False)
    ax.set_title(xlabel)
    ax.set_ylabel("")
    ax.set_xlabel("")
    sns.despine(ax=ax)
//  [python]
def plot_ax(ax, data, xlabel):
    palette = ["#5847AD", "#F7B449"]
    kws = dict(orient="v", errorbar="sd", palette=palette, width=0.6)
    sns.barplot(data=data, ax=ax, **kws)
    data.melt().pipe((sns.scatterplot, "data"), y="value", x="variable", ax=ax,
                     zorder=100, color="grey", alpha=0.5)
    ax.get_xticklabels()[0].set_fontweight("bold")
    ax.tick_params(axis="x", rotation=45)
    ax.tick_params(bottom=False)
    ax.set_title(xlabel)
    ax.set_ylabel("")
    ax.set_xlabel("")
    sns.utils.despine(ax=ax)