jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def histogram(self):
        """

        :return:
        """


        seaborn.set_context(context='poster')
        data = self.model_selection_data

        data = data.unstack()
        data = data.reset_index()
        data = data.rename(columns={'level_0': 'Model',
                                    'level_1': 'Metric',
                                    0: 'Score'})
        for label, df in data.groupby(by=['Metric']):
            fig = plt.figure()
            for label2, df2 in df.groupby(by='Model'):

                plot_data = df2['Score'].dropna()
                ax = seaborn.distplot(
                    plot_data,
                    bins=self.bins,
                    hist=self.hist, kde=self.kde, rug=self.rug, fit=None,
                    hist_kws=self.hist_kws, kde_kws=self.kde_kws, rug_kws=self.rug_kws,
                    color=self.color, vertical=self.vertical, norm_hist=self.norm_hist,
                    axlabel=self.axlabel, label=self.model_labels[label2], ax=self.ax)
                if self.title:
                    plt.title("{} Score (n={})".format(label, plot_data.shape[0]))
                plt.ylabel("Frequency")
                plt.xlabel("Score".format(label, plot_data.shape[0]))
                if self.despine:
                    seaborn.utils.despine(fig=fig, top=True, right=True)

                if self.legend:
                    plt.legend(loc=(self.legend_loc))

            if self.savefig:
                save_dir = os.path.join(self.results_directory, 'ModelSelectionGraphs')
                if os.path.isdir(save_dir) != True:
                    os.mkdir(save_dir)
                os.chdir(save_dir)
                fname = os.path.join(save_dir, 'Histogram_{}_{}.{}'.format(label2, label, self.ext))
                plt.savefig(fname, dpi=self.dpi, bbox_inches='tight')
                LOG.info('histograms saved to : "{}"'.format(fname))
                self.to_csv(self.filename)

            if self.show:
                plt.show()
//  [python]
def silhouette_Elbow_Kmeans(dt_trans,Max=9,Min=2):
    s = []
    for n_clusters in range(Min,Max):
        kmeans = KMeans(n_clusters=n_clusters)
        kmeans.fit(dt_trans)

        labels = kmeans.labels_
        centroids = kmeans.cluster_centers_

        s.append(silhouette_score(dt_trans, labels, metric='euclidean'))

    x = range(Min,Max)
    plt.plot(x,s)
    plt.ylabel("Silouette")
    plt.xlabel("k")
    plt.title("Silouette for K-means cell's behaviour")
    sns.despine()
//  [python]
def silhouette_Elbow_Kmeans(dt_trans,Max=9,Min=2):
    s = []
    for n_clusters in range(Min,Max):
        kmeans = KMeans(n_clusters=n_clusters)
        kmeans.fit(dt_trans)

        labels = kmeans.labels_
        centroids = kmeans.cluster_centers_

        s.append(silhouette_score(dt_trans, labels, metric='euclidean'))

    x = range(Min,Max)
    plt.plot(x,s)
    plt.ylabel("Silouette")
    plt.xlabel("k")
    plt.title("Silouette for K-means cell's behaviour")
    sns.utils.despine()
//  [python]
def plot_elevations(df, output_file="elevations.png"):
    # Create a new figure
    plt.figure()

    # Compute activity start times (for facet ordering)
    start_times = (
        df.groupby("name").agg({"time": "min"}).reset_index().sort_values("time")
    )
    ncol = math.ceil(math.sqrt(len(start_times)))

    # Create facets
    p = sns.FacetGrid(
        data=df,
        col="name",
        col_wrap=ncol,
        col_order=start_times["name"],
        sharex=False,
        sharey=True,
    )

    # Add activities
    p = p.map(plt.plot, "dist", "ele", color="black", linewidth=4)

    # Update plot aesthetics
    p.set(xlabel=None)
    p.set(ylabel=None)
    p.set(xticks=[])
    p.set(yticks=[])
    p.set(xticklabels=[])
    p.set(yticklabels=[])
    p.set_titles(col_template="", row_template="")
    sns.despine(left=True, bottom=True)
    plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)
    plt.savefig(output_file)
//  [python]
def plot_elevations(df, output_file="elevations.png"):
    # Create a new figure
    plt.figure()

    # Compute activity start times (for facet ordering)
    start_times = (
        df.groupby("name").agg({"time": "min"}).reset_index().sort_values("time")
    )
    ncol = math.ceil(math.sqrt(len(start_times)))

    # Create facets
    p = sns.FacetGrid(
        data=df,
        col="name",
        col_wrap=ncol,
        col_order=start_times["name"],
        sharex=False,
        sharey=True,
    )

    # Add activities
    p = p.map(plt.plot, "dist", "ele", color="black", linewidth=4)

    # Update plot aesthetics
    p.set(xlabel=None)
    p.set(ylabel=None)
    p.set(xticks=[])
    p.set(yticks=[])
    p.set(xticklabels=[])
    p.set(yticklabels=[])
    p.set_titles(col_template="", row_template="")
    sns.utils.despine(left=True, bottom=True)
    plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)
    plt.savefig(output_file)
//  [python]
def plot_activations():
    fig, axes = plt.subplots(2, 5, sharex=True, sharey=True)
    fns = [
        Affine(),
        Tanh(),
        Sigmoid(),
        ReLU(),
        LeakyReLU(),
        ELU(),
        Exponential(),
        SELU(),
        HardSigmoid(),
        SoftPlus(),
    ]

    for ax, fn in zip(axes.flatten(), fns):
        X = np.linspace(-3, 3, 100).astype(float).reshape(100, 1)
        ax.plot(X, fn(X), label=r"$y$", alpha=1.0)
        ax.plot(X, fn.grad(X), label=r"$\frac{dy}{dx}$", alpha=1.0)
        ax.plot(X, fn.grad2(X), label=r"$\frac{d^2 y}{dx^2}$", alpha=1.0)
        ax.hlines(0, -3, 3, lw=1, linestyles="dashed", color="k")
        ax.vlines(0, -1.2, 1.2, lw=1, linestyles="dashed", color="k")
        ax.set_ylim(-1.1, 1.1)
        ax.set_xlim(-3, 3)
        ax.set_xticks([])
        ax.set_yticks([-1, 0, 1])
        ax.xaxis.set_visible(False)
        #  ax.yaxis.set_visible(False)
        ax.set_title("{}".format(fn))
        ax.legend(frameon=False)
        sns.despine(left=True, bottom=True)

    fig.set_size_inches(10, 5)
    plt.tight_layout()
    plt.savefig("img/plot.png", dpi=300)
    plt.close("all")
//  [python]
def plot_activations():
    fig, axes = plt.subplots(2, 5, sharex=True, sharey=True)
    fns = [
        Affine(),
        Tanh(),
        Sigmoid(),
        ReLU(),
        LeakyReLU(),
        ELU(),
        Exponential(),
        SELU(),
        HardSigmoid(),
        SoftPlus(),
    ]

    for ax, fn in zip(axes.flatten(), fns):
        X = np.linspace(-3, 3, 100).astype(float).reshape(100, 1)
        ax.plot(X, fn(X), label=r"$y$", alpha=1.0)
        ax.plot(X, fn.grad(X), label=r"$\frac{dy}{dx}$", alpha=1.0)
        ax.plot(X, fn.grad2(X), label=r"$\frac{d^2 y}{dx^2}$", alpha=1.0)
        ax.hlines(0, -3, 3, lw=1, linestyles="dashed", color="k")
        ax.vlines(0, -1.2, 1.2, lw=1, linestyles="dashed", color="k")
        ax.set_ylim(-1.1, 1.1)
        ax.set_xlim(-3, 3)
        ax.set_xticks([])
        ax.set_yticks([-1, 0, 1])
        ax.xaxis.set_visible(False)
        #  ax.yaxis.set_visible(False)
        ax.set_title("{}".format(fn))
        ax.legend(frameon=False)
        sns.utils.despine(left=True, bottom=True)

    fig.set_size_inches(10, 5)
    plt.tight_layout()
    plt.savefig("img/plot.png", dpi=300)
    plt.close("all")
//  [python]
sns.boxplot(
    planets, x="distance", y="method", hue="method",
    whis=[0, 100], width=.6, palette="vlag"
)

# Add in points to show each observation
sns.stripplot(planets, x="distance", y="method", size=4, color=".3")

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

# Add in points to show each observation
sns.stripplot(planets, x="distance", y="method", size=4, color=".3")

# Tweak the visual presentation
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.utils.despine(trim=True, left=True)
//  [python]
def projection_plot(comp_df, species, savename1, savename2):

    # setup figure
    fig, axs = plt.subplots(2, 1, figsize=(7, 5))

    # shared genome fraction
    ax = axs[0]
    sdf = comp_df["fraction of total genome length"]
    ax_boxplot(sdf, ax)

    # add species name
    sp_name = beautify_species(species)
    ax.text(0, 0, f"{sp_name}", weight="bold", size="large")

    # shared segment sizes
    ax = axs[1]
    sdf = comp_df["average segment size (bp)"]
    ax_boxplot(sdf, ax)

    # add titles
    axs[0].set_xlabel("fraction of total genome length")
    axs[1].set_xlabel("average segment size (bp)")

    # tweak axes
    ax.set_xscale("log")

    # despine and save
    sns.despine(fig)
    plt.tight_layout()
    plt.savefig(savename1)
    plt.savefig(savename2)
    plt.close(fig)
//  [python]
def projection_plot(comp_df, species, savename1, savename2):

    # setup figure
    fig, axs = plt.subplots(2, 1, figsize=(7, 5))

    # shared genome fraction
    ax = axs[0]
    sdf = comp_df["fraction of total genome length"]
    ax_boxplot(sdf, ax)

    # add species name
    sp_name = beautify_species(species)
    ax.text(0, 0, f"{sp_name}", weight="bold", size="large")

    # shared segment sizes
    ax = axs[1]
    sdf = comp_df["average segment size (bp)"]
    ax_boxplot(sdf, ax)

    # add titles
    axs[0].set_xlabel("fraction of total genome length")
    axs[1].set_xlabel("average segment size (bp)")

    # tweak axes
    ax.set_xscale("log")

    # despine and save
    sns.utils.despine(fig)
    plt.tight_layout()
    plt.savefig(savename1)
    plt.savefig(savename2)
    plt.close(fig)
//  [python]
def plot_mean_trace(mean_trace, frame_rate, ylabel='dF/F', legend_label=None, color='k', interval_sec=1, xlims=[-4, 4],
                    ax=None):
    xlim = [0, xlims[1] + np.abs(xlims[0])]
    if ax is None:
        fig, ax = plt.subplots()
    # times = np.arange(0, len(mean_trace), 1)
    ax.plot(mean_trace, label=legend_label, linewidth=3, color=color)
    xticks, xticklabels = sf.get_xticks_xticklabels(mean_trace, frame_rate, interval_sec, window=xlims)
    ax.set_xticks(xticks)
    if interval_sec < 1:
        ax.set_xticklabels(xticklabels)
    else:
        ax.set_xticklabels([int(x) for x in xticklabels])
    ax.set_xlim(xlim[0] * int(frame_rate), xlim[1] * int(frame_rate))
    ax.set_xlabel('time (sec)')
    ax.set_ylabel(ylabel)
    sns.despine(ax=ax)
    return ax
//  [python]
def plot_mean_trace(mean_trace, frame_rate, ylabel='dF/F', legend_label=None, color='k', interval_sec=1, xlims=[-4, 4],
                    ax=None):
    xlim = [0, xlims[1] + np.abs(xlims[0])]
    if ax is None:
        fig, ax = plt.subplots()
    # times = np.arange(0, len(mean_trace), 1)
    ax.plot(mean_trace, label=legend_label, linewidth=3, color=color)
    xticks, xticklabels = sf.get_xticks_xticklabels(mean_trace, frame_rate, interval_sec, window=xlims)
    ax.set_xticks(xticks)
    if interval_sec < 1:
        ax.set_xticklabels(xticklabels)
    else:
        ax.set_xticklabels([int(x) for x in xticklabels])
    ax.set_xlim(xlim[0] * int(frame_rate), xlim[1] * int(frame_rate))
    ax.set_xlabel('time (sec)')
    ax.set_ylabel(ylabel)
    sns.utils.despine(ax=ax)
    return ax
//  [python]
def plot_mean_trace_from_mean_df(cell_data, frame_rate=31., ylabel='dF/F', legend_label=None, color='k', interval_sec=1,
                                 xlims=[-4, 4],
                                 ax=None, plot_sem=True, width=3):
    xlim = [0, xlims[1] + np.abs(xlims[0])]
    if ax is None:
        fig, ax = plt.subplots()
    trace = cell_data.mean_trace.values[0]
    times = np.arange(0, len(trace), 1)
    sem = cell_data.sem_trace.values[0]
    ax.plot(trace, label=legend_label, linewidth=width, color=color)
    if plot_sem:
        ax.fill_between(times, trace + sem, trace - sem, alpha=0.5, color=color)
    xticks, xticklabels = sf.get_xticks_xticklabels(trace, frame_rate, interval_sec, window=xlims)
    ax.set_xticks(xticks)
    if interval_sec >= 1:
        ax.set_xticklabels([int(x) for x in xticklabels])
    else:
        ax.set_xticklabels(xticklabels)
    ax.set_xlim(xlim[0] * int(frame_rate), xlim[1] * int(frame_rate))
    ax.set_xlabel('time (s)')
    ax.set_ylabel(ylabel)
    sns.despine(ax=ax)
    return ax
//  [python]
def plot_mean_trace_from_mean_df(cell_data, frame_rate=31., ylabel='dF/F', legend_label=None, color='k', interval_sec=1,
                                 xlims=[-4, 4],
                                 ax=None, plot_sem=True, width=3):
    xlim = [0, xlims[1] + np.abs(xlims[0])]
    if ax is None:
        fig, ax = plt.subplots()
    trace = cell_data.mean_trace.values[0]
    times = np.arange(0, len(trace), 1)
    sem = cell_data.sem_trace.values[0]
    ax.plot(trace, label=legend_label, linewidth=width, color=color)
    if plot_sem:
        ax.fill_between(times, trace + sem, trace - sem, alpha=0.5, color=color)
    xticks, xticklabels = sf.get_xticks_xticklabels(trace, frame_rate, interval_sec, window=xlims)
    ax.set_xticks(xticks)
    if interval_sec >= 1:
        ax.set_xticklabels([int(x) for x in xticklabels])
    else:
        ax.set_xticklabels(xticklabels)
    ax.set_xlim(xlim[0] * int(frame_rate), xlim[1] * int(frame_rate))
    ax.set_xlabel('time (s)')
    ax.set_ylabel(ylabel)
    sns.utils.despine(ax=ax)
    return ax
//  [python]
def plot_categories_by_topic_boxplots(labels, 
                                      topic_distributions, 
                                      topic_keys, 
                                      target_topic_index,
                                      output_path=None,
                                      target_labels=None,
                                      dim=None):
    
    if not target_labels:
        target_labels = list(set(labels))
                   
    # Combine the labels and distributions into a dataframe.
    dicts_to_plot = []
    for _label, _distribution in zip(labels, topic_distributions):
        if not target_labels or _label in target_labels:
            dicts_to_plot.append({'Probability': float(_distribution[target_topic_index]),
                                  'Category': _label,
                                  'Topic': ' '.join(topic_keys[target_topic_index][:5])})
    df_to_plot = pd.DataFrame(dicts_to_plot)

    # Show the final plot.
    if dim:
        plt.figure(figsize=dim)
    sns.set(style='ticks', font_scale=1.2)
    sns.boxplot(data=df_to_plot,
                x='Category',
                y='Probability',
                color='skyblue')  
    sns.despine()
    plt.xticks(rotation=45, ha='right')
    plt.title('Topic: ' + ' '.join(topic_keys[target_topic_index][:5]))
    plt.tight_layout()
    if output_path:
        plt.savefig(output_path)
    plt.show()
//  [python]
def plot_categories_by_topic_boxplots(labels, 
                                      topic_distributions, 
                                      topic_keys, 
                                      target_topic_index,
                                      output_path=None,
                                      target_labels=None,
                                      dim=None):
    
    if not target_labels:
        target_labels = list(set(labels))
                   
    # Combine the labels and distributions into a dataframe.
    dicts_to_plot = []
    for _label, _distribution in zip(labels, topic_distributions):
        if not target_labels or _label in target_labels:
            dicts_to_plot.append({'Probability': float(_distribution[target_topic_index]),
                                  'Category': _label,
                                  'Topic': ' '.join(topic_keys[target_topic_index][:5])})
    df_to_plot = pd.DataFrame(dicts_to_plot)

    # Show the final plot.
    if dim:
        plt.figure(figsize=dim)
    sns.set(style='ticks', font_scale=1.2)
    sns.boxplot(data=df_to_plot,
                x='Category',
                y='Probability',
                color='skyblue')  
    sns.utils.despine()
    plt.xticks(rotation=45, ha='right')
    plt.title('Topic: ' + ' '.join(topic_keys[target_topic_index][:5]))
    plt.tight_layout()
    if output_path:
        plt.savefig(output_path)
    plt.show()
//  [python]
def show_fig(std, ax, title):
    """Create a plot of normally distributed data in a given axis"""

    for ii in range(3):
        data = stats.norm(centers[ii], std).rvs(numData)
        offset = ii*numData
        ax.plot( offset+np.arange(numData), data, '.', ms=8)

    ax.xaxis.set_ticks([50,150,250])
    ax.set_xticklabels(['Group1', 'Group2', 'Group3'])
    ax.set_title(title)
    sns.despine()
//  [python]
def show_fig(std, ax, title):
    """Create a plot of normally distributed data in a given axis"""

    for ii in range(3):
        data = stats.norm(centers[ii], std).rvs(numData)
        offset = ii*numData
        ax.plot( offset+np.arange(numData), data, '.', ms=8)

    ax.xaxis.set_ticks([50,150,250])
    ax.set_xticklabels(['Group1', 'Group2', 'Group3'])
    ax.set_title(title)
    sns.utils.despine()
//  [python]
def top_calls_plot(df, sample):
	df["Top 100 not enriched not depleted"] = df["Top 100 not depleted"] - df["Top 100 enriched"]
	print(df)	

	ax, tool_order, col_list = prepare_for_simul(2)
	# Create correct bars
	#ax1 = plt.bar(r, meandf['Correct'], edgecolor='gray', width=bar_width, label="Correct mapping", yerr=stddf['AllCorrectPerc'])
	# Create incorrect bars
	#ax2 = plt.bar(r, meandf['Incorrect'], bottom=meandf['Correct'], edgecolor='gray', width=bar_width, label="Incorrect mapping", yerr=stddf['AllIncorrectPerc'])
	#ax = sns.barplot(x = 'Tool', y = 'Top 100 enriched', alpha=1.0, data=df, order=tool_order)
	
	ax = sns.barplot(x = 'Tool', y = 'Top 100 not depleted', alpha=1.0, data=df, order=tool_order, color='b')
	ax = sns.barplot(x = 'Tool', y = 'Top 100 enriched', alpha=1.0, data=df, order=tool_order, color='g')

	sns.despine(left=True, right=True, top=True)

	matplotlib.pyplot.sca(ax)
	plt.xticks(rotation=90)

	#ax.get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
	#plt.grid(b=True, which='major', color='gray', linewidth=1.0)
	#plt.grid(b=True, which='minor', color='gray', linewidth=0.5)
	#plt.gca().xaxis.grid(False)
	
	ax.set(xlabel='Methods', ylabel='Number of calls')
	ax.set_ylim(top=100)

	matplotlib.style.use('seaborn')
	name_to_color = {
					'Enriched':   'green',
					'Not depleted':   'blue',
					}

	patches = [matplotlib.patches.Patch(color=v, label=k) for k,v in name_to_color.items()]
	matplotlib.pyplot.legend(handles=patches,loc = "upper right", bbox_to_anchor=(1,1) )
			

	## There is no labels, need to define the labels
	#legend_labels  = ['Enriched', 'Not depleted']

	## Create the legend patches
	#legend_patches = [matplotlib.patches.Patch(color=C, label=L) for
    #              C, L in zip([item.get_facecolor() for item in Boxes],
    #                          legend_labels)]

	## Plot the legend
	#plt.legend(handles=legend_patches)

	plt.savefig('{}_top100_enriched_notdepleted.png'.format(sample), bbox_inches='tight', dpi=600)
//  [python]
def top_calls_plot(df, sample):
	df["Top 100 not enriched not depleted"] = df["Top 100 not depleted"] - df["Top 100 enriched"]
	print(df)	

	ax, tool_order, col_list = prepare_for_simul(2)
	# Create correct bars
	#ax1 = plt.bar(r, meandf['Correct'], edgecolor='gray', width=bar_width, label="Correct mapping", yerr=stddf['AllCorrectPerc'])
	# Create incorrect bars
	#ax2 = plt.bar(r, meandf['Incorrect'], bottom=meandf['Correct'], edgecolor='gray', width=bar_width, label="Incorrect mapping", yerr=stddf['AllIncorrectPerc'])
	#ax = sns.barplot(x = 'Tool', y = 'Top 100 enriched', alpha=1.0, data=df, order=tool_order)
	
	ax = sns.barplot(x = 'Tool', y = 'Top 100 not depleted', alpha=1.0, data=df, order=tool_order, color='b')
	ax = sns.barplot(x = 'Tool', y = 'Top 100 enriched', alpha=1.0, data=df, order=tool_order, color='g')

	seaborn.utils.despine(left=True, right=True, top=True)

	matplotlib.pyplot.sca(ax)
	plt.xticks(rotation=90)

	#ax.get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
	#plt.grid(b=True, which='major', color='gray', linewidth=1.0)
	#plt.grid(b=True, which='minor', color='gray', linewidth=0.5)
	#plt.gca().xaxis.grid(False)
	
	ax.set(xlabel='Methods', ylabel='Number of calls')
	ax.set_ylim(top=100)

	matplotlib.style.use('seaborn')
	name_to_color = {
					'Enriched':   'green',
					'Not depleted':   'blue',
					}

	patches = [matplotlib.patches.Patch(color=v, label=k) for k,v in name_to_color.items()]
	matplotlib.pyplot.legend(handles=patches,loc = "upper right", bbox_to_anchor=(1,1) )
			

	## There is no labels, need to define the labels
	#legend_labels  = ['Enriched', 'Not depleted']

	## Create the legend patches
	#legend_patches = [matplotlib.patches.Patch(color=C, label=L) for
    #              C, L in zip([item.get_facecolor() for item in Boxes],
    #                          legend_labels)]

	## Plot the legend
	#plt.legend(handles=legend_patches)

	plt.savefig('{}_top100_enriched_notdepleted.png'.format(sample), bbox_inches='tight', dpi=600)
//  [python]
def plot_behavior_for_session(dataset, cache_dir):
    flashes = dataset.stimulus_presentations.copy()
    flashes = ut.annotate_flashes_with_reward_rate(dataset)
    figsize = (15, 4)
    fig, ax = plt.subplots(figsize=figsize)
    ax.plot(dataset.stimulus_timestamps, dataset.running_speed.running_speed.values)
    ax.set_ylabel('running speed(cm/s)')
    ax2 = ax.twinx()
    ax2.plot(flashes.start_time.values, flashes.reward_rate.values, color='red')
    ax2.set_ylabel('reward rate')
    ax = plot_behavior_events(dataset, ax)
    sns.despine(ax=ax2, right=False)
    ax.set_xlabel('time in session (seconds)')
    ax.set_title(dataset.analysis_folder)
    fig.tight_layout()
    save_figure(fig, figsize, dataset.analysis_dir, 'behavior', 'behavior')
    save_figure(fig, figsize, os.path.join(cache_dir, 'summary_figures'), 'behavior', dataset.analysis_folder)
//  [python]
def plot_behavior_for_session(dataset, cache_dir):
    flashes = dataset.stimulus_presentations.copy()
    flashes = ut.annotate_flashes_with_reward_rate(dataset)
    figsize = (15, 4)
    fig, ax = plt.subplots(figsize=figsize)
    ax.plot(dataset.stimulus_timestamps, dataset.running_speed.running_speed.values)
    ax.set_ylabel('running speed(cm/s)')
    ax2 = ax.twinx()
    ax2.plot(flashes.start_time.values, flashes.reward_rate.values, color='red')
    ax2.set_ylabel('reward rate')
    ax = plot_behavior_events(dataset, ax)
    sns.utils.despine(ax=ax2, right=False)
    ax.set_xlabel('time in session (seconds)')
    ax.set_title(dataset.analysis_folder)
    fig.tight_layout()
    save_figure(fig, figsize, dataset.analysis_dir, 'behavior', 'behavior')
    save_figure(fig, figsize, os.path.join(cache_dir, 'summary_figures'), 'behavior', dataset.analysis_folder)
//  [python]
def box_and_whisker(
    X_train, top_preds, example, display_feature_names={}, display_units={}, **kwargs
):
    """Create interpretability graphic"""
    color = kwargs.get("bar_color", "lightblue")

    f, axes = plt.subplots(dpi=300, nrows=len(top_preds), figsize=(4, 5))
    sns.despine(
        fig=f,
        ax=axes,
        top=True,
        right=True,
        left=True,
        bottom=False,
        offset=None,
        trim=False,
    )

    box_plots = []
    for ax, v in zip(axes, top_preds):
        box_plot = ax.boxplot(
            x=X_train[v], vert=False, whis=[0, 100], patch_artist=True, widths=0.35
        )
        box_plots.append(box_plot)
        ax.annotate(
            display_feature_names.get(v, v) + " (" + display_units.get(v, v) + ")",
            xy=(0.9, 1.15),
            xycoords="axes fraction",
        )
        ax.annotate(
            rounding(example[v]),
            xy=(0.9, 0.7),
            xycoords="axes fraction",
            fontsize=6,
            color="red",
        )
        # plot vertical lines
        ax.axvline(x=example[v], color="red", zorder=5)

        # Remove y tick labels
        ax.set_yticks(
            [],
        )

    # fill with colors
    for bplot in box_plots:
        for patch in bplot["boxes"]:
            patch.set_facecolor(color)
        for line in bplot["means"]:
            line.set_color(color)

    plt.subplots_adjust(wspace=5.75)
    f.suptitle("Training Set Distribution for Top Predictors")
    axes[0].set_title(
        "Vertical red bars show current values for this object",
        fontsize=8,
        pad=25,
        color="red",
    )
    f.tight_layout()

    return f, axes
//  [python]
def box_and_whisker(
    X_train, top_preds, example, display_feature_names={}, display_units={}, **kwargs
):
    """Create interpretability graphic"""
    color = kwargs.get("bar_color", "lightblue")

    f, axes = plt.subplots(dpi=300, nrows=len(top_preds), figsize=(4, 5))
    sns.utils.despine(
        fig=f,
        ax=axes,
        top=True,
        right=True,
        left=True,
        bottom=False,
        offset=None,
        trim=False,
    )

    box_plots = []
    for ax, v in zip(axes, top_preds):
        box_plot = ax.boxplot(
            x=X_train[v], vert=False, whis=[0, 100], patch_artist=True, widths=0.35
        )
        box_plots.append(box_plot)
        ax.annotate(
            display_feature_names.get(v, v) + " (" + display_units.get(v, v) + ")",
            xy=(0.9, 1.15),
            xycoords="axes fraction",
        )
        ax.annotate(
            rounding(example[v]),
            xy=(0.9, 0.7),
            xycoords="axes fraction",
            fontsize=6,
            color="red",
        )
        # plot vertical lines
        ax.axvline(x=example[v], color="red", zorder=5)

        # Remove y tick labels
        ax.set_yticks(
            [],
        )

    # fill with colors
    for bplot in box_plots:
        for patch in bplot["boxes"]:
            patch.set_facecolor(color)
        for line in bplot["means"]:
            line.set_color(color)

    plt.subplots_adjust(wspace=5.75)
    f.suptitle("Training Set Distribution for Top Predictors")
    axes[0].set_title(
        "Vertical red bars show current values for this object",
        fontsize=8,
        pad=25,
        color="red",
    )
    f.tight_layout()

    return f, axes
//  [python]
def plot_mean_trace_from_mean_df(cell_data, frame_rate=31., ylabel='dF/F', legend_label=None, color='k', interval_sec=1,
                                 xlims=[-4, 4],
                                 ax=None, plot_sem=True, width=3):
    xlim = [0, xlims[1] + np.abs(xlims[0])]
    if ax is None:
        fig, ax = plt.subplots()
    trace = cell_data.mean_trace.values[0]
    times = np.arange(0, len(trace), 1)
    sem = cell_data.sem_trace.values[0]
    ax.plot(trace, label=legend_label, linewidth=width, color=color)
    if plot_sem:
        ax.fill_between(times, trace + sem, trace - sem, alpha=0.5, color=color)
    xticks, xticklabels = get_xticks_xticklabels(trace, frame_rate, interval_sec, window=xlims)
    ax.set_xticks(xticks)
    if interval_sec >= 1:
        ax.set_xticklabels([int(x) for x in xticklabels])
    else:
        ax.set_xticklabels(xticklabels)
    ax.set_xlim(xlim[0] * int(frame_rate), xlim[1] * int(frame_rate))
    ax.set_xlabel('time (s)')
    ax.set_ylabel(ylabel)
    sns.despine(ax=ax)
    return ax
//  [python]
def plot_mean_trace_from_mean_df(cell_data, frame_rate=31., ylabel='dF/F', legend_label=None, color='k', interval_sec=1,
                                 xlims=[-4, 4],
                                 ax=None, plot_sem=True, width=3):
    xlim = [0, xlims[1] + np.abs(xlims[0])]
    if ax is None:
        fig, ax = plt.subplots()
    trace = cell_data.mean_trace.values[0]
    times = np.arange(0, len(trace), 1)
    sem = cell_data.sem_trace.values[0]
    ax.plot(trace, label=legend_label, linewidth=width, color=color)
    if plot_sem:
        ax.fill_between(times, trace + sem, trace - sem, alpha=0.5, color=color)
    xticks, xticklabels = get_xticks_xticklabels(trace, frame_rate, interval_sec, window=xlims)
    ax.set_xticks(xticks)
    if interval_sec >= 1:
        ax.set_xticklabels([int(x) for x in xticklabels])
    else:
        ax.set_xticklabels(xticklabels)
    ax.set_xlim(xlim[0] * int(frame_rate), xlim[1] * int(frame_rate))
    ax.set_xlabel('time (s)')
    ax.set_ylabel(ylabel)
    sns.utils.despine(ax=ax)
    return ax
//  [python]
def plot_mean_trace_with_variability(traces, frame_rate, ylabel='dF/F', label=None, color='k', interval_sec=1,
                                     xlims=[-4, 4], ax=None, flashes=True):
    #     xlim = [xlims[0] + np.abs(xlims[0]), xlims[1] + np.abs(xlims[0])]
    if ax is None:
        fig, ax = plt.subplots()
    if len(traces) > 0:
        mean_trace = np.mean(traces, axis=0)
        # times = np.arange(0, len(mean_trace), 1)
        # sem = (traces.std()) / np.sqrt(float(len(traces)))
        for trace in traces:
            ax.plot(trace, linewidth=1, color='gray')
        ax.plot(mean_trace, label=label, linewidth=3, color=color, zorder=100)
        xticks, xticklabels = get_xticks_xticklabels(mean_trace, frame_rate, interval_sec, window=xlims)
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticklabels)
        ax.set_xlim(0, (np.abs(xlims[0]) + xlims[1]) * int(frame_rate))
        ax.set_xlabel('time (sec)')
        ax.set_ylabel(ylabel)
        sns.despine(ax=ax)
    return ax
//  [python]
def plot_mean_trace_with_variability(traces, frame_rate, ylabel='dF/F', label=None, color='k', interval_sec=1,
                                     xlims=[-4, 4], ax=None, flashes=True):
    #     xlim = [xlims[0] + np.abs(xlims[0]), xlims[1] + np.abs(xlims[0])]
    if ax is None:
        fig, ax = plt.subplots()
    if len(traces) > 0:
        mean_trace = np.mean(traces, axis=0)
        # times = np.arange(0, len(mean_trace), 1)
        # sem = (traces.std()) / np.sqrt(float(len(traces)))
        for trace in traces:
            ax.plot(trace, linewidth=1, color='gray')
        ax.plot(mean_trace, label=label, linewidth=3, color=color, zorder=100)
        xticks, xticklabels = get_xticks_xticklabels(mean_trace, frame_rate, interval_sec, window=xlims)
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticklabels)
        ax.set_xlim(0, (np.abs(xlims[0]) + xlims[1]) * int(frame_rate))
        ax.set_xlabel('time (sec)')
        ax.set_ylabel(ylabel)
        sns.utils.despine(ax=ax)
    return ax
//  [python]
def DisplayBoxplot(self,data,column1,column2): 
        column1=column1.title()
        column2=column2.title()
        LabelDictCol = {'Critic Rating':'critic_rating','Audience Rating':'audience_rating','Budget In Millions':'budget_in_millions','Genre':'genre','Year':'year'}        
        fig,ax=plt.subplots() 
        fig.set_size_inches(11.7,8.27)
        sns.boxplot(data=data,x=LabelDictCol[column1],y=LabelDictCol[column2],palette='vlag',whis="range")
        ax.yaxis.grid(True)
        ax.xaxis.grid(True)
        plt.title('{} Vs {} Boxplot'.format(column1,column2),fontsize=20)
        plt.xlabel('{}'.format(column1),fontsize=15)
        plt.ylabel('{}'.format(column2),fontsize=15)
        plt.xticks(rotation=30)
        sns.despine(trim=True, left=True)
        plt.show()
//  [python]
def DisplayBoxplot(self,data,column1,column2): 
        column1=column1.title()
        column2=column2.title()
        LabelDictCol = {'Critic Rating':'critic_rating','Audience Rating':'audience_rating','Budget In Millions':'budget_in_millions','Genre':'genre','Year':'year'}        
        fig,ax=plt.subplots() 
        fig.set_size_inches(11.7,8.27)
        sns.boxplot(data=data,x=LabelDictCol[column1],y=LabelDictCol[column2],palette='vlag',whis="range")
        ax.yaxis.grid(True)
        ax.xaxis.grid(True)
        plt.title('{} Vs {} Boxplot'.format(column1,column2),fontsize=20)
        plt.xlabel('{}'.format(column1),fontsize=15)
        plt.ylabel('{}'.format(column2),fontsize=15)
        plt.xticks(rotation=30)
        sns.utils.despine(trim=True, left=True)
        plt.show()
//  [python]
def plot_box( self, fname_out = None):      
        sns.boxplot(x="Method", y="r2", data=self.df_best_expand, palette="PRGn")
        sns.despine(offset=10, trim=True)
        plt.ylabel( r"$r^2$")
        plt.xlabel( "Methods")

        if fname_out is not None:
            plt.savefig( fname_out) # index should be stored.
        elif self.fname is not None:
            fname_out = self.fname[:-4] + '_box.eps'
            print( 'Default: the figure of self.df_best_expand is saved to', fname_out)
            plt.savefig( fname_out)
//  [python]
def plot_box( self, fname_out = None):      
        sns.boxplot(x="Method", y="r2", data=self.df_best_expand, palette="PRGn")
        sns.utils.despine(offset=10, trim=True)
        plt.ylabel( r"$r^2$")
        plt.xlabel( "Methods")

        if fname_out is not None:
            plt.savefig( fname_out) # index should be stored.
        elif self.fname is not None:
            fname_out = self.fname[:-4] + '_box.eps'
            print( 'Default: the figure of self.df_best_expand is saved to', fname_out)
            plt.savefig( fname_out)
//  [python]
def plot_series(series, x_label, y_label, sort=False, scale="linear",
                bar=False, colour=None, name=None):

    figure_name = saving.build_figure_name("series", name)

    if not colour:
        colour = style.STANDARD_PALETTE[0]

    series_length = series.shape[0]

    x = numpy.linspace(0, series_length, series_length)

    y_log = scale == "log"

    if sort:
        # Sort descending
        series = numpy.sort(series)[::-1]
        x_label = "sorted " + x_label
        figure_name += "-sorted"

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.despine()

    if bar:
        axis.bar(x, series, log=y_log, color=colour, alpha=0.4)
    else:
        axis.plot(x, series, color=colour)
        axis.set_yscale(scale)

    axis.set_xlabel(capitalise_string(x_label))
    axis.set_ylabel(capitalise_string(y_label))

    return figure, figure_name
//  [python]
def plot_series(series, x_label, y_label, sort=False, scale="linear",
                bar=False, colour=None, name=None):

    figure_name = saving.build_figure_name("series", name)

    if not colour:
        colour = style.STANDARD_PALETTE[0]

    series_length = series.shape[0]

    x = numpy.linspace(0, series_length, series_length)

    y_log = scale == "log"

    if sort:
        # Sort descending
        series = numpy.sort(series)[::-1]
        x_label = "sorted " + x_label
        figure_name += "-sorted"

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.utils.despine()

    if bar:
        axis.bar(x, series, log=y_log, color=colour, alpha=0.4)
    else:
        axis.plot(x, series, color=colour)
        axis.set_yscale(scale)

    axis.set_xlabel(capitalise_string(x_label))
    axis.set_ylabel(capitalise_string(y_label))

    return figure, figure_name
//  [python]
def plot_behavior_for_epoch(dataset, start_time, duration, exclude_running=False, legend=False,
                            save_figures=False, save_dir=None, ax=None):
    xlim = (start_time, start_time + duration + 1)
    running_speed = dataset.running_speed.speed.values
    running_times = dataset.running_speed.timestamps.values
    if ax is None:
        figsize = (15, 2)
        fig, ax = plt.subplots(figsize=figsize)
    if exclude_running:
        folder = 'behavior_epoch_licks'
        ax.set_ylim(0, 1)
        ax = plot_licks_and_rewards(dataset, ax)
        ax.set_ylim(-0.4, 0.5)
        ax.set_ylabel('')
        ax.set_yticklabels([])
        ax.tick_params(axis='x', left='off')
        ax.tick_params(axis='y', left='off')
        sns.despine(ax=ax, top=False, right=False)
    else:
        folder = 'behavior_epoch_running_licks'
        ax.plot(running_times, running_speed, color=sns.color_palette()[0], label='run_speed')
        ax.set_ylabel('run speed\n(cm/s)')
        ax = plot_licks_and_rewards(dataset, ax, behavior_only=False)
        ymin, ymax = ax.get_ylim()
        ax.set_ylim(ymin * 1.1, ymax)
    if legend:
        ax.legend(bbox_to_anchor=(1, .46), ncol=3)
    ax = add_stim_color_span(dataset, ax, xlim=xlim)
    ax.set_xlim(xlim)
    ax.set_xlabel('time (seconds)')
    ax.set_xticks(np.arange(xlim[0], xlim[1], 10))
    xticklabels = np.arange(xlim[0], xlim[1], 10) - xlim[0]
    ax.set_xticklabels([int(x) for x in xticklabels])
    ax.set_title(dataset.analysis_folder + ' - ' + str(start_time), fontsize=14)
    plt.gcf().subplots_adjust(bottom=0.3)
    if save_figures:
        if save_dir:
            save_figure(fig, figsize, save_dir, folder, dataset.analysis_folder + '_' + str(start_time))
        save_figure(fig, figsize, dataset.analysis_dir, folder, str(start_time))
        plt.close()
    return ax
//  [python]
def plot_behavior_for_epoch(dataset, start_time, duration, exclude_running=False, legend=False,
                            save_figures=False, save_dir=None, ax=None):
    xlim = (start_time, start_time + duration + 1)
    running_speed = dataset.running_speed.speed.values
    running_times = dataset.running_speed.timestamps.values
    if ax is None:
        figsize = (15, 2)
        fig, ax = plt.subplots(figsize=figsize)
    if exclude_running:
        folder = 'behavior_epoch_licks'
        ax.set_ylim(0, 1)
        ax = plot_licks_and_rewards(dataset, ax)
        ax.set_ylim(-0.4, 0.5)
        ax.set_ylabel('')
        ax.set_yticklabels([])
        ax.tick_params(axis='x', left='off')
        ax.tick_params(axis='y', left='off')
        sns.utils.despine(ax=ax, top=False, right=False)
    else:
        folder = 'behavior_epoch_running_licks'
        ax.plot(running_times, running_speed, color=sns.color_palette()[0], label='run_speed')
        ax.set_ylabel('run speed\n(cm/s)')
        ax = plot_licks_and_rewards(dataset, ax, behavior_only=False)
        ymin, ymax = ax.get_ylim()
        ax.set_ylim(ymin * 1.1, ymax)
    if legend:
        ax.legend(bbox_to_anchor=(1, .46), ncol=3)
    ax = add_stim_color_span(dataset, ax, xlim=xlim)
    ax.set_xlim(xlim)
    ax.set_xlabel('time (seconds)')
    ax.set_xticks(np.arange(xlim[0], xlim[1], 10))
    xticklabels = np.arange(xlim[0], xlim[1], 10) - xlim[0]
    ax.set_xticklabels([int(x) for x in xticklabels])
    ax.set_title(dataset.analysis_folder + ' - ' + str(start_time), fontsize=14)
    plt.gcf().subplots_adjust(bottom=0.3)
    if save_figures:
        if save_dir:
            save_figure(fig, figsize, save_dir, folder, dataset.analysis_folder + '_' + str(start_time))
        save_figure(fig, figsize, dataset.analysis_dir, folder, str(start_time))
        plt.close()
    return ax
//  [python]
def plot_boxplot(df, dataset):
    data = df[df["dataset"] == dataset]

    sns.set_theme(style="ticks")

    f, ax = plt.subplots(figsize=(6, 4))

    # Plot the orbital period with horizontal boxes
    sns.boxplot(x="MAE", y="benchmark", data=data,
                whis=[0, 100], width=.6, palette="vlag")

    # Add in points to show each observation
    sns.stripplot(x="MAE", y="benchmark", data=data,
                  size=4, color=".3", linewidth=0)

    # Tweak the visual presentation
    ax.xaxis.grid(True)
    ax.set(ylabel="")
    sns.despine(trim=True, left=True)
    return f
//  [python]
def plot_boxplot(df, dataset):
    data = df[df["dataset"] == dataset]

    sns.set_theme(style="ticks")

    f, ax = plt.subplots(figsize=(6, 4))

    # Plot the orbital period with horizontal boxes
    sns.boxplot(x="MAE", y="benchmark", data=data,
                whis=[0, 100], width=.6, palette="vlag")

    # Add in points to show each observation
    sns.stripplot(x="MAE", y="benchmark", data=data,
                  size=4, color=".3", linewidth=0)

    # Tweak the visual presentation
    ax.xaxis.grid(True)
    ax.set(ylabel="")
    sns.utils.despine(trim=True, left=True)
    return f
//  [python]
def plot_behavior_annotated(dataset, xmin=1800, duration=20, plot_reward_rate=False, cache_dir=None, show=True):
    xlim = (xmin, xmin + duration)
    all_trials = dataset.all_trials.copy()
    trial_starts = all_trials[all_trials.trial_type != 'aborted'].starttime.values
    ts = trial_starts[(trial_starts > xlim[0])]
    ts = ts[(ts < xlim[1])]
    abort_starts = all_trials[all_trials.trial_type == 'aborted'].starttime.values
    ab = abort_starts[(abort_starts > xlim[0])]
    ab = ab[(ab < xlim[1])]
    flashes = dataset.stimulus_presentations.copy()
    flashes = ut.annotate_flashes_with_reward_rate(dataset)
    figsize = (15, 4)
    fig, ax = plt.subplots(figsize=figsize)
    ax = add_stim_color_span(dataset, ax=ax, xlim=xlim)
    ax.plot(dataset.stimulus_timestamps, dataset.running_speed.running_speed.values, label='run speed', linewidth=2)
    ax.set_ylabel('running speed(cm/s)')
    if plot_reward_rate:
        ax2 = ax.twinx()
        ax2.plot(flashes.start_time.values, flashes.reward_rate.values, color=sns.color_palette()[4],
                 label='reward rate')
        ax2.set_ylabel('reward rate')
        sns.despine(ax=ax2, right=False)
    ax = plot_behavior_events(dataset, ax, linewidth=4)
    ymin, ymax = ax.get_ylim()
    for a in ab:
        ax.vlines(x=a, ymin=ymin, ymax=ymax, color='red', linewidth=2)
    if len(ab) > 0:
        a = ab[0]
        ax.vlines(x=a, ymin=ymin, ymax=ymax, color='red', linewidth=2, label='aborted trial start')
    for t in ts:
        ax.vlines(x=t, ymin=ymin, ymax=ymax, color='green', linewidth=2)
    if len(ts) > 0:
        t = ts[0]
        ax.vlines(x=t, ymin=ymin, ymax=ymax, color='green', linewidth=2, label='go/catch trial start')
    ax.set_xlabel('time in session (seconds)')
    ax.set_title(dataset.analysis_folder)
    ax.set_xlim(xlim)
    ax.legend(loc='upper left', fontsize='x-small')
    #     ax.legend(bbox_to_anchor=(0.05,1.1), ncol=5, loc='upper left')
    fig.tight_layout()
    fig.subplots_adjust(top=.8)
    save_figure(fig, figsize, dataset.analysis_dir, 'behavior', 'behavior_' + str(xlim[0]))
    if cache_dir:
        save_figure(fig, figsize, os.path.join(cache_dir, 'summary_figures'), 'behavior',
                    dataset.analysis_folder + '_' + str(xlim[0]))
    if not show:
        plt.close()
//  [python]
def plot_behavior_annotated(dataset, xmin=1800, duration=20, plot_reward_rate=False, cache_dir=None, show=True):
    xlim = (xmin, xmin + duration)
    all_trials = dataset.all_trials.copy()
    trial_starts = all_trials[all_trials.trial_type != 'aborted'].starttime.values
    ts = trial_starts[(trial_starts > xlim[0])]
    ts = ts[(ts < xlim[1])]
    abort_starts = all_trials[all_trials.trial_type == 'aborted'].starttime.values
    ab = abort_starts[(abort_starts > xlim[0])]
    ab = ab[(ab < xlim[1])]
    flashes = dataset.stimulus_presentations.copy()
    flashes = ut.annotate_flashes_with_reward_rate(dataset)
    figsize = (15, 4)
    fig, ax = plt.subplots(figsize=figsize)
    ax = add_stim_color_span(dataset, ax=ax, xlim=xlim)
    ax.plot(dataset.stimulus_timestamps, dataset.running_speed.running_speed.values, label='run speed', linewidth=2)
    ax.set_ylabel('running speed(cm/s)')
    if plot_reward_rate:
        ax2 = ax.twinx()
        ax2.plot(flashes.start_time.values, flashes.reward_rate.values, color=sns.color_palette()[4],
                 label='reward rate')
        ax2.set_ylabel('reward rate')
        sns.utils.despine(ax=ax2, right=False)
    ax = plot_behavior_events(dataset, ax, linewidth=4)
    ymin, ymax = ax.get_ylim()
    for a in ab:
        ax.vlines(x=a, ymin=ymin, ymax=ymax, color='red', linewidth=2)
    if len(ab) > 0:
        a = ab[0]
        ax.vlines(x=a, ymin=ymin, ymax=ymax, color='red', linewidth=2, label='aborted trial start')
    for t in ts:
        ax.vlines(x=t, ymin=ymin, ymax=ymax, color='green', linewidth=2)
    if len(ts) > 0:
        t = ts[0]
        ax.vlines(x=t, ymin=ymin, ymax=ymax, color='green', linewidth=2, label='go/catch trial start')
    ax.set_xlabel('time in session (seconds)')
    ax.set_title(dataset.analysis_folder)
    ax.set_xlim(xlim)
    ax.legend(loc='upper left', fontsize='x-small')
    #     ax.legend(bbox_to_anchor=(0.05,1.1), ncol=5, loc='upper left')
    fig.tight_layout()
    fig.subplots_adjust(top=.8)
    save_figure(fig, figsize, dataset.analysis_dir, 'behavior', 'behavior_' + str(xlim[0]))
    if cache_dir:
        save_figure(fig, figsize, os.path.join(cache_dir, 'summary_figures'), 'behavior',
                    dataset.analysis_folder + '_' + str(xlim[0]))
    if not show:
        plt.close()
//  [python]
sns.set_style("white")
plt.figure(figsize=(4,2))
sns.violinplot(x='N',y='x',data=df,cut=0,inner='stick')
plt.ylabel("Observations of $S_N$")
sns.despine()
//  [python]
def adjust_subfigure(subfig):
    subfig[0].subplots_adjust(
        hspace=0.8, wspace=1.4, left=0.32, right=0.94, top=0.92, bottom=0.12
    )
    subfig[1].subplots_adjust(
        hspace=0.8, wspace=0.4, left=0.2, right=0.7, top=0.92, bottom=0.08
    )

    subfig[0].text(
        -0.025, 0.58, "unspliced expression", size=7, rotation="vertical", va="center"
    )
    subfig[0].text(
        0.552, 0.58, "spliced expression", size=7, rotation="vertical", va="center"
    )

    sns.despine()
//  [python]
def adjust_subfigure(subfig):
    subfig[0].subplots_adjust(
        hspace=0.8, wspace=1.4, left=0.32, right=0.94, top=0.92, bottom=0.12
    )
    subfig[1].subplots_adjust(
        hspace=0.8, wspace=0.4, left=0.2, right=0.7, top=0.92, bottom=0.08
    )

    subfig[0].text(
        -0.025, 0.58, "unspliced expression", size=7, rotation="vertical", va="center"
    )
    subfig[0].text(
        0.552, 0.58, "spliced expression", size=7, rotation="vertical", va="center"
    )

    sns.utils.despine()
//  [python]
def plot_with_custum_ci_SP_highnumber(df, x=300, y=0.51):
    '''use the reduced dataframe as input (e.g. use only brain variants).'''
    
    df = df[df.MAX_MAF_25_BOOL == True]
    df = df.sort_values(by=['MAF'], ascending=False)
    df = df.reset_index(drop=True).reset_index()
    plt.plot((df.iloc[:,0] + 1), df['MAF'], color='g')
    plt.plot((df.iloc[:,0] + 1), df['UPPER_CI'],
             color='0.5')
    plt.plot((df.iloc[:,0] + 1), df['LOWER_CI'],
             color='0.5')
    plt.xlabel('Ranked Mosaic Variants')
    plt.ylabel('Allelic Fraction')
    plt.xlim(0,x)
    plt.ylim(0,y)
    sns.despine(offset=5, trim=True)
    plt.show()
//  [python]
def plot_with_custum_ci_SP_highnumber(df, x=300, y=0.51):
    '''use the reduced dataframe as input (e.g. use only brain variants).'''
    
    df = df[df.MAX_MAF_25_BOOL == True]
    df = df.sort_values(by=['MAF'], ascending=False)
    df = df.reset_index(drop=True).reset_index()
    plt.plot((df.iloc[:,0] + 1), df['MAF'], color='g')
    plt.plot((df.iloc[:,0] + 1), df['UPPER_CI'],
             color='0.5')
    plt.plot((df.iloc[:,0] + 1), df['LOWER_CI'],
             color='0.5')
    plt.xlabel('Ranked Mosaic Variants')
    plt.ylabel('Allelic Fraction')
    plt.xlim(0,x)
    plt.ylim(0,y)
    sns.utils.despine(offset=5, trim=True)
    plt.show()
//  [python]
def plot_change_by_pos(diffs_by_context,plottype='box'):
    fig = plt.figure(figsize=(6,4))
    changes_by_position = {'position':[],'base':[],'diff':[]}
    for lab in diffs_by_context:
        for context in diffs_by_context[lab]:
            for entry in diffs_by_context[lab][context]:
                for pos,diff in enumerate(entry[:-1]):
                    changes_by_position['position'].append(pos+1)
                    changes_by_position['base'].append(lab)
                    changes_by_position['diff'].append(diff)
    dPos = pd.DataFrame(changes_by_position)
    if plottype == 'box':
        sns.boxplot(x="position", y="diff", hue="base", data=dPos, palette=[cols[base],cols[methbase]])
    elif plottype == 'violin':
        sns.violinplot(x="position",y="diff", hue="base", data=dPos, palette=[cols[base],cols[methbase]])
    sns.despine(trim=False)
    plt.xlabel('Adenine Position in 6-mer')
    plt.ylabel('Measured - Expected Current (pA)')
    plt.ylim([-20,20])
    plt.legend(title='',loc='upper center', bbox_to_anchor=(0.5, 1.05),
          ncol=3, fancybox=True)
    plt.savefig('change_by_position_box.pdf',transparent=True,dpi=500, bbox_inches='tight')