jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
ax = plt.subplot(111)
sns.scatterplot(
    data=emp_scores,
    x='connectome',
    y='z-score',
    s=30,
    c='black',
    ax=ax
)
sns.stripplot(
    data=null_scores,
    x='connectome',
    y='z-score',
    # width=0.5,
    s=2.5,
    jitter=0.3,
    ax=ax
)
ax.set_ylim(-2.5, 12.5)
sns.utils.despine(offset=10, trim=True,
            top=True, bottom=False,
            right=True, left=False)
//  [python]
def plot_discovered_occurred_ratio_locations(dataframe, file_path=''):
  """Plot the discovered incidents/occurred ratio for each location."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.despine()

  sns.set(style='ticks')
  sns.catplot(
      x='param_value',
      y='discovered/occurred',
      data=dataframe,
      hue='agent_type',
      height=plot_height,
      aspect=aspect_ratio,
      s=8)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '.pdf', bbox_inches='tight')

  sns.set(style='ticks')
  sns.catplot(
      x='param_value',
      y='discovered/occurred weighted',
      data=dataframe,
      hue='agent_type',
      height=plot_height,
      aspect=aspect_ratio,
      s=8)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred weighted', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_weighted.pdf', bbox_inches='tight')
//  [python]
def plot_discovered_occurred_ratio_locations(dataframe, file_path=''):
  """Plot the discovered incidents/occurred ratio for each location."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.utils.despine()

  sns.set(style='ticks')
  sns.catplot(
      x='param_value',
      y='discovered/occurred',
      data=dataframe,
      hue='agent_type',
      height=plot_height,
      aspect=aspect_ratio,
      s=8)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '.pdf', bbox_inches='tight')

  sns.set(style='ticks')
  sns.catplot(
      x='param_value',
      y='discovered/occurred weighted',
      data=dataframe,
      hue='agent_type',
      height=plot_height,
      aspect=aspect_ratio,
      s=8)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred weighted', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_weighted.pdf', bbox_inches='tight')
//  [python]
def plot_influence_score(self, topK: int = 20):
        """
        Plot the gene influence score of top-k driver regulators.
        """
        if self.driver_regulator is None:
            raise ValueError(
                f'Did not find the result of driver regulators. Run `cefcon.NetModel.driver_regulators` first.'
            )
        data_for_plot = self.driver_regulator[self.driver_regulator['is_driver_regulator']]
        data_for_plot = data_for_plot[0:topK]

        plt.figure(figsize=(1.5, topK * 0.15))
        #sns.set_theme(style='ticks', font_scale=0.5)

        ax = sns.barplot(x='influence_score', y=data_for_plot.index, data=data_for_plot, orient='h',
                         palette=sns.color_palette(f"ch:start=.5,rot=-.5,reverse=1,dark=0.4", n_colors=topK))
        ax.set_title(self.name)
        ax.set_xlabel('Influence score')
        ax.set_ylabel('Driver regulators')
        ax.xaxis.set_minor_locator(ticker.NullLocator())
        ax.yaxis.set_minor_locator(ticker.NullLocator())
        sns.despine()

        plt.show()
//  [python]
def plot_influence_score(self, topK: int = 20):
        """
        Plot the gene influence score of top-k driver regulators.
        """
        if self.driver_regulator is None:
            raise ValueError(
                f'Did not find the result of driver regulators. Run `cefcon.NetModel.driver_regulators` first.'
            )
        data_for_plot = self.driver_regulator[self.driver_regulator['is_driver_regulator']]
        data_for_plot = data_for_plot[0:topK]

        plt.figure(figsize=(1.5, topK * 0.15))
        #sns.set_theme(style='ticks', font_scale=0.5)

        ax = sns.barplot(x='influence_score', y=data_for_plot.index, data=data_for_plot, orient='h',
                         palette=sns.color_palette(f"ch:start=.5,rot=-.5,reverse=1,dark=0.4", n_colors=topK))
        ax.set_title(self.name)
        ax.set_xlabel('Influence score')
        ax.set_ylabel('Driver regulators')
        ax.xaxis.set_minor_locator(ticker.NullLocator())
        ax.yaxis.set_minor_locator(ticker.NullLocator())
        sns.utils.despine()

        plt.show()
//  [python]
def plot_cloudsort():
    df = pd.DataFrame(
        [
            [2016, 1.44, "NADSort"],
            [2022, 1.15, "NADSort"],
            [2022, 0.97, "LibShuffle-CloudSort"],
            # [2022, 0.74, "Theoretical Limit"],
        ],
        columns=["year", "time", "system"],
    )
    ax = sns.scatterplot(
        data=df,
        x="year",
        y="time",
        hue="system",
        palette=["gray", set2[2]],
        style="system",
        markers={"NADSort": "s", "LibShuffle-CloudSort": "D"},
        s=100,
    )
    ax.set(ylim=(0, 1.50))
    # prepend y axis labels with a dollar sign
    ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter("\\${x:,.2f}"))
    # draw a line between the first two points
    ax.plot([2016, 2022], [1.44, 1.15], color="gray", linewidth=2, linestyle="--")
    # remove the legend title
    ax.legend().set_title(None)
    # despine
    sns.despine()

    fig = ax.get_figure()
    plt.xlabel("Year", fontsize=20)
    plt.ylabel("Cost/TB", fontsize=20)
    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.legend(fontsize=20)
    filename = "cloudsort.pdf"
    print(filename)
    fig.savefig(filename, bbox_inches="tight")
//  [python]
def plot_cloudsort():
    df = pd.DataFrame(
        [
            [2016, 1.44, "NADSort"],
            [2022, 1.15, "NADSort"],
            [2022, 0.97, "LibShuffle-CloudSort"],
            # [2022, 0.74, "Theoretical Limit"],
        ],
        columns=["year", "time", "system"],
    )
    ax = sns.scatterplot(
        data=df,
        x="year",
        y="time",
        hue="system",
        palette=["gray", set2[2]],
        style="system",
        markers={"NADSort": "s", "LibShuffle-CloudSort": "D"},
        s=100,
    )
    ax.set(ylim=(0, 1.50))
    # prepend y axis labels with a dollar sign
    ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter("\\${x:,.2f}"))
    # draw a line between the first two points
    ax.plot([2016, 2022], [1.44, 1.15], color="gray", linewidth=2, linestyle="--")
    # remove the legend title
    ax.legend().set_title(None)
    # despine
    sns.utils.despine()

    fig = ax.get_figure()
    plt.xlabel("Year", fontsize=20)
    plt.ylabel("Cost/TB", fontsize=20)
    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.legend(fontsize=20)
    filename = "cloudsort.pdf"
    print(filename)
    fig.savefig(filename, bbox_inches="tight")
//  [python]
def density(self, **kwargs: Dict) -> Any:
        df = self.duration.get_dataframe()
        ax = sns.displot(
            df,
            x=Durations.COLUMN_STAY_DURATION,
            kind="kde",
            cut=0,
            **kwargs
        )
        plt.xlabel("Duration (in days)")
        sns.despine()
        return ax
//  [python]
def density(self, **kwargs: Dict) -> Any:
        df = self.duration.get_dataframe()
        ax = sns.displot(
            df,
            x=Durations.COLUMN_STAY_DURATION,
            kind="kde",
            cut=0,
            **kwargs
        )
        plt.xlabel("Duration (in days)")
        sns.utils.despine()
        return ax
//  [python]
def histogram(self, **kwargs: Dict) -> Any:
        df = self.duration.get_dataframe()
        ax = sns.histplot(
            df,
            x=Durations.COLUMN_STAY_DURATION,
            edgecolor=".3",
            linewidth=.5,
            **kwargs
        )
        ax.set_xlabel("Duration (in days)")
        ax.set_ylabel("Count")
        sns.despine()
        return ax
//  [python]
def histogram(self, **kwargs: Dict) -> Any:
        df = self.duration.get_dataframe()
        ax = sns.histplot(
            df,
            x=Durations.COLUMN_STAY_DURATION,
            edgecolor=".3",
            linewidth=.5,
            **kwargs
        )
        ax.set_xlabel("Duration (in days)")
        ax.set_ylabel("Count")
        sns.utils.despine()
        return ax
//  [python]
def show_SD(axis, xi, yi, text):
    """Show the area covered by 1/2/3 SDs"""

    fc = '#DDDDDD'
    axis.plot(x,y)
    axis.fill_between(xi, yi, facecolor=fc)

    axis.text(0, 0.05, text, horizontalalignment='center', fontsize=18)
    axis.set_xlim([-3.5, 3.5])
    axis.set_ylim([-0.0, 0.5])
    sns.despine(ax=axis, left=True)
    axis.set_yticks([])
//  [python]
def show_SD(axis, xi, yi, text):
    """Show the area covered by 1/2/3 SDs"""

    fc = '#DDDDDD'
    axis.plot(x,y)
    axis.fill_between(xi, yi, facecolor=fc)

    axis.text(0, 0.05, text, horizontalalignment='center', fontsize=18)
    axis.set_xlim([-3.5, 3.5])
    axis.set_ylim([-0.0, 0.5])
    sns.utils.despine(ax=axis, left=True)
    axis.set_yticks([])
//  [python]
def plot_borderless(img, name, cmap=None):
    dpi=400
    fig = plt.figure(figsize=(img.shape[1]/dpi,img.shape[0]/dpi))
    plt.imshow(img,interpolation='nearest',cmap=cmap)
    sns.despine(top=True,right=True,left=True,bottom=True)
    ax = plt.gca()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.set_frame_on(False)
    ax.set_position([0, 0, 1, 1])
    plt.margins(0,0)
    plt.savefig(name, dpi=dpi, pad_inches=0, bbox_inches=0)
    plt.close(fig)
//  [python]
def plot_borderless(img, name, cmap=None):
    dpi=400
    fig = plt.figure(figsize=(img.shape[1]/dpi,img.shape[0]/dpi))
    plt.imshow(img,interpolation='nearest',cmap=cmap)
    sns.utils.despine(top=True,right=True,left=True,bottom=True)
    ax = plt.gca()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.set_frame_on(False)
    ax.set_position([0, 0, 1, 1])
    plt.margins(0,0)
    plt.savefig(name, dpi=dpi, pad_inches=0, bbox_inches=0)
    plt.close(fig)
//  [python]
sns.barplot(x='Condition', y='Spike Frequency', ci=68, data=df)
# ci=68 uses the SEM instead of STD
# sns.boxplot(x='Condition', y='Spike Frequency', data=df)
# sns.catplot(x='Condition', y='Spike Frequency', kind='bar', data=df)
# some reason, changing the figure size does not affect catplot
# sns.pointplot(x='Condition', y='Spike Frequency', data=df,
# 	dodge=True, join=False)
sns.swarmplot(x='Condition', y='Spike Frequency', data=df, color='grey')


plt.ylabel('Spike Rate (Hz)')
plt.xlabel('')
sns.despine(top=True, right=True)
//  [python]
sns.barplot(x='Condition', y='Spike Frequency', ci=68, data=df)
sns.swarmplot(x='Condition', y='Spike Frequency', data=df, color='grey')

plt.ylabel('Spike Rate (Hz)')
plt.xlabel('')
sns.utils.despine(top=True, right=True)
//  [python]
def customize(func):
    """
    Decorator to set plotting context and axes style during function call.
    """
    @wraps(func)
    def call_w_context(*args, **kwargs):
        set_context = kwargs.pop('set_context', True)
        if set_context:
            with plotting_context(), axes_style():
                sns.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)
    return call_w_context
//  [python]
def customize(func):
    """
    Decorator to set plotting context and axes style during function call.
    """
    @wraps(func)
    def call_w_context(*args, **kwargs):
        set_context = kwargs.pop('set_context', True)
        if set_context:
            with plotting_context(), axes_style():
                sns.utils.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)
    return call_w_context
//  [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 violins(axis):
    '''
    violinplot example from https://seaborn.pydata.org/examples/simple_violinplots.html
    '''
    # Create a random dataset across several variables
    rs = np.random.default_rng(0)
    n, p = 40, 8
    d = rs.normal(0, 2, (n, p))
    d += np.log(np.arange(1, p + 1)) * -5 + 10

    # Show each distribution with both violins and points
    sns.violinplot(data=d, palette="light:g", inner="points", orient="h", ax=axis)
    sns.despine()
//  [python]
def violins(axis):
    '''
    violinplot example from https://seaborn.pydata.org/examples/simple_violinplots.html
    '''
    # Create a random dataset across several variables
    rs = np.random.default_rng(0)
    n, p = 40, 8
    d = rs.normal(0, 2, (n, p))
    d += np.log(np.arange(1, p + 1)) * -5 + 10

    # Show each distribution with both violins and points
    sns.violinplot(data=d, palette="light:g", inner="points", orient="h", ax=axis)
    sns.utils.despine()
//  [python]
def plot_all_models_gmm(models, data, l, u, bins, out_file):
    """
    Plot a bunch of GMMs.

    :param models: list of GMM model objects
    :param data: Ks array
    :param l: lower Ks limit
    :param u: upper Ks limit
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    fig, axes = plt.subplots(len(models), 3, figsize=(15, 3 * len(models)))
    for i, model in enumerate(models):
        plot_mixture(model, data, axes[i, 0], l, u, bins=bins)
        plot_mixture(model, data, axes[i, 1], log=True, l=np.log(l + 0.0001),
                     u=np.log(u), bins=bins)
        plot_probs(model, axes[i, 2], l, u)
    sns.despine(offset=5)
    fig.tight_layout()
    fig.savefig(out_file)
//  [python]
def plot_all_models_gmm(models, data, l, u, bins, out_file):
    """
    Plot a bunch of GMMs.

    :param models: list of GMM model objects
    :param data: Ks array
    :param l: lower Ks limit
    :param u: upper Ks limit
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    fig, axes = plt.subplots(len(models), 3, figsize=(15, 3 * len(models)))
    for i, model in enumerate(models):
        plot_mixture(model, data, axes[i, 0], l, u, bins=bins)
        plot_mixture(model, data, axes[i, 1], log=True, l=np.log(l + 0.0001),
                     u=np.log(u), bins=bins)
        plot_probs(model, axes[i, 2], l, u)
    sns.utils.despine(offset=5)
    fig.tight_layout()
    fig.savefig(out_file)
//  [python]
def plot_all_models_bgmm(models, data, l, u, bins, out_file):
    """
    Plot a bunch of BGMMs.

    :param models: list of GMM model objects
    :param data: Ks array
    :param l: lower Ks limit
    :param u: upper Ks limit
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    fig, axes = plt.subplots(len(models), 4, figsize=(20, 3 * len(models)))
    for i, model in enumerate(models):
        plot_mixture(model, data, axes[i, 0], l, u, bins=bins)
        plot_mixture(model, data, axes[i, 1], log=True, l=np.log(l + 0.0001),
                     u=np.log(u), bins=bins)
        plot_probs(model, axes[i, 2], l, u)
        plot_bars_weights(model, axes[i, 3])
    sns.despine(offset=5)
    fig.tight_layout()
    fig.savefig(out_file)
//  [python]
def plot_all_models_bgmm(models, data, l, u, bins, out_file):
    """
    Plot a bunch of BGMMs.

    :param models: list of GMM model objects
    :param data: Ks array
    :param l: lower Ks limit
    :param u: upper Ks limit
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    fig, axes = plt.subplots(len(models), 4, figsize=(20, 3 * len(models)))
    for i, model in enumerate(models):
        plot_mixture(model, data, axes[i, 0], l, u, bins=bins)
        plot_mixture(model, data, axes[i, 1], log=True, l=np.log(l + 0.0001),
                     u=np.log(u), bins=bins)
        plot_probs(model, axes[i, 2], l, u)
        plot_bars_weights(model, axes[i, 3])
    sns.utils.despine(offset=5)
    fig.tight_layout()
    fig.savefig(out_file)
//  [python]
def reflected_kde(df, min_ks, max_ks, bandwidth, bins, out_file):
    """
    Perform Kernel density estimation (KDE) with reflected data.
    The data frame is assumed to be grouped already by 'Node'.

    :param df: data frame
    :param min_ks: minimum Ks value (best is to use 0, for reflection purposes)
    :param max_ks: maximum Ks value
    :param bandwidth: bandwidth (None results in Scott's rule of thumb)
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    ks = np.array(df['Ks'])
    ks_reflected = reflect(ks)
    fig, ax = plt.subplots(figsize=(9, 4))
    if bandwidth:
        ax = sns.distplot(
                ks_reflected, bins=bins * 2, ax=ax,
                hist_kws={"rwidth": 0.8, "color": "k", "alpha": 0.2},
                kde_kws={"bw": bandwidth},
                color="k"
        )
    else:
        ax = sns.distplot(
                ks_reflected, bins=bins * 2, ax=ax,
                hist_kws={"rwidth": 0.8, "color": "k", "alpha": 0.2},
                color="k"
        )
    ax.set_xlim(min_ks, max_ks)
    sns.despine(offset=5, trim=False)
    ax.set_ylabel("Density")
    ax.set_xlabel("$K_{\mathrm{S}}$")
    fig.savefig(out_file, bbox_inches='tight')
//  [python]
def reflected_kde(df, min_ks, max_ks, bandwidth, bins, out_file):
    """
    Perform Kernel density estimation (KDE) with reflected data.
    The data frame is assumed to be grouped already by 'Node'.

    :param df: data frame
    :param min_ks: minimum Ks value (best is to use 0, for reflection purposes)
    :param max_ks: maximum Ks value
    :param bandwidth: bandwidth (None results in Scott's rule of thumb)
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    ks = np.array(df['Ks'])
    ks_reflected = reflect(ks)
    fig, ax = plt.subplots(figsize=(9, 4))
    if bandwidth:
        ax = sns.distplot(
                ks_reflected, bins=bins * 2, ax=ax,
                hist_kws={"rwidth": 0.8, "color": "k", "alpha": 0.2},
                kde_kws={"bw": bandwidth},
                color="k"
        )
    else:
        ax = sns.distplot(
                ks_reflected, bins=bins * 2, ax=ax,
                hist_kws={"rwidth": 0.8, "color": "k", "alpha": 0.2},
                color="k"
        )
    ax.set_xlim(min_ks, max_ks)
    sns.utils.despine(offset=5, trim=False)
    ax.set_ylabel("Density")
    ax.set_xlabel("$K_{\mathrm{S}}$")
    fig.savefig(out_file, bbox_inches='tight')
//  [python]
def plot_bar(d1, d2, label1=None, label2=None, err=None, width=0.65,
             average='mean', lw=4, ylim=None, figsize=None, **plt_kwargs):
    """Plot a bar graph."""

    _, ax = plt.subplots(figsize=figsize)

    if err:
        err = [np.nanstd(d1), np.nanstd(d2)]

    avg_func = AVG_FUNCS_NAN[average]

    ax.bar([0.5, 1.5], [avg_func(d1), avg_func(d2)], yerr=err,
           tick_label=[label1, label2], width=width, **plt_kwargs)

    ax.set_xlim([0, 2])

    if ylim:
        ax.set_ylim(ylim)

    ax.set_yticks([]);
    if not label1:
        ax.set_xticks([]);

    sns.despine(ax=ax, top=True, right=True)
    [ax.spines[side].set_linewidth(lw) for side in ['left', 'bottom']]
//  [python]
def plot_bar(d1, d2, label1=None, label2=None, err=None, width=0.65,
             average='mean', lw=4, ylim=None, figsize=None, **plt_kwargs):
    """Plot a bar graph."""

    _, ax = plt.subplots(figsize=figsize)

    if err:
        err = [np.nanstd(d1), np.nanstd(d2)]

    avg_func = AVG_FUNCS_NAN[average]

    ax.bar([0.5, 1.5], [avg_func(d1), avg_func(d2)], yerr=err,
           tick_label=[label1, label2], width=width, **plt_kwargs)

    ax.set_xlim([0, 2])

    if ylim:
        ax.set_ylim(ylim)

    ax.set_yticks([]);
    if not label1:
        ax.set_xticks([]);

    sns.utils.despine(ax=ax, top=True, right=True)
    [ax.spines[side].set_linewidth(lw) for side in ['left', 'bottom']]
//  [python]
def start_plotting(fig_size, fig_pos, style="white", rc=None, despine=False):
    with sns.axes_style(style, rc):
        fig = plt.figure(figsize=fig_size)
        if not fig_pos:
            ax = fig.add_subplot(111)
        else:
            ax = fig.add_axes(fig_pos)
    if despine:
        sns.despine(left=True)
    return fig, ax
//  [python]
def start_plotting(fig_size, fig_pos, style="white", rc=None, despine=False):
    with sns.axes_style(style, rc):
        fig = plt.figure(figsize=fig_size)
        if not fig_pos:
            ax = fig.add_subplot(111)
        else:
            ax = fig.add_axes(fig_pos)
    if despine:
        sns.utils.despine(left=True)
    return fig, ax
//  [python]
def plot_power_by_shape(rdsyms, mean_beta, std_beta, selected, cmap):
    """Plot measured oscillatory power across waveform shape values."""""

    _, ax_sym = plt.subplots(figsize=(5, 3))
    ax_sym.plot(rdsyms, mean_beta, "k.-")

    for ind, rd in enumerate(selected):
        idx = np.argmin(np.abs(rdsyms - rd))
        ax_sym.plot(rdsyms[idx], mean_beta[idx], ".",
                    color=cmap[ind], markersize=15, markeredgecolor="w")

    rdsyms = np.hstack([0.48, rdsyms, 1.0])
    mean_beta = np.hstack([mean_beta[0], mean_beta, mean_beta[-1]])
    std_beta = np.hstack([std_beta[0], std_beta, std_beta[-1]])

    ax_sym.fill_between(rdsyms, mean_beta - std_beta, mean_beta + std_beta,
                        facecolor="k", alpha=0.25, edgecolor=None)
    ax_sym.set(xlabel="rise-decay asymmetry", xticks=np.arange(0.5, 1.01, 0.1),
               ylabel="average beta power", yticks=[], xlim=(0.48, 1.0))
    sns.despine(ax=ax_sym)
//  [python]
def plot_power_by_shape(rdsyms, mean_beta, std_beta, selected, cmap):
    """Plot measured oscillatory power across waveform shape values."""""

    _, ax_sym = plt.subplots(figsize=(5, 3))
    ax_sym.plot(rdsyms, mean_beta, "k.-")

    for ind, rd in enumerate(selected):
        idx = np.argmin(np.abs(rdsyms - rd))
        ax_sym.plot(rdsyms[idx], mean_beta[idx], ".",
                    color=cmap[ind], markersize=15, markeredgecolor="w")

    rdsyms = np.hstack([0.48, rdsyms, 1.0])
    mean_beta = np.hstack([mean_beta[0], mean_beta, mean_beta[-1]])
    std_beta = np.hstack([std_beta[0], std_beta, std_beta[-1]])

    ax_sym.fill_between(rdsyms, mean_beta - std_beta, mean_beta + std_beta,
                        facecolor="k", alpha=0.25, edgecolor=None)
    ax_sym.set(xlabel="rise-decay asymmetry", xticks=np.arange(0.5, 1.01, 0.1),
               ylabel="average beta power", yticks=[], xlim=(0.48, 1.0))
    sns.utils.despine(ax=ax_sym)
//  [python]
def plot(args):
  plt.figure(figsize=(4,3), dpi=300)
  sns.despine(left=True, bottom=True)
  datas = load(args.source, args.names, args.labels, args.smooth, args.bin_size)
  for ignore_string in args.ignore_strings:
    datas = [d for d in datas if not ignore_string in d[0]]
  lines = []
  max_y = args.max_y
  min_y = args.min_y
  max_x = args.max_x
  min_x = 1e10

  for i, data in enumerate(datas):
    label, x, y_mean, y_std = data
    color = args.colors[i]
    if np.sum(y_std):
      y_upper = y_mean + y_std
      y_lower = y_mean - y_std
      plt.fill_between(
          x, list(y_lower), list(y_upper), interpolate=True, facecolor=color, linewidth=0.0, alpha=0.2
      )
    linestyle = args.line_styles[i]
    marker = args.markers[i]
    markersize = args.markersizes[i]
    markevery=int(max_x/500)
    line = plt.plot(x, list(y_mean), linewidth=2.0, label=label, color=color, markersize=markersize, marker=marker, markevery=markevery, linestyle=linestyle)
    lines.append(line[0])
    if max(x) < min_x:
      min_x = max(x)


  xticks = np.arange(0, max_x+1, max_x // 8 )
  ignore_even = lambda s, i: s if i %2 == 0 else ''
  if 'Millions' in args.xlabel:
    xlabels = [ignore_even('{:0.2f}'.format(float(x) / 100000000. * args.time_steps_per_episode).rstrip('0').rstrip('.'),
                i) for i, x in enumerate(xticks)]
  elif 'Thousands' in args.xlabel:
    xlabels = [ignore_even('{:0.2f}'.format(float(x) / 100000. * args.time_steps_per_episode).rstrip('0').rstrip('.'),
                i) for i, x in enumerate(xticks)]
  #xlabels[-1] += 'M'
  plt.xticks(xticks, xlabels, fontsize=args.label_size)
  if args.xlabel is None:
    plt.xlabel('Placeholder', fontsize=args.label_size, color='white')
  else:
    plt.xlabel(args.xlabel, fontsize=args.label_size)

  if hasattr(args, 'y_values'):
    plt.yticks(args.y_values, args.y_labels, fontsize=args.label_size)
  if args.ylabel is None:
    plt.ylabel('')
  else:
    plt.ylabel(args.ylabel, fontsize=args.label_size)
  
  plt.ylim(min_y, max_y)
  plt.xlim(0, max_x)
  plt.legend(fancybox=True, framealpha=0.7, loc=args.legend_loc, fontsize=args.legend_size, frameon=True, facecolor='white', borderaxespad=1.)
  plt.title(args.title, fontsize=args.title_size)
  plt.tight_layout(pad=0.0) # Make room for the xlabel
  plt.savefig(args.output, format='png', dpi=600) # Need to do savefig before plt.show() otherwise PDF file will be blank
  print("DONE {}".format(args.output))
//  [python]
def plot(args):
  plt.figure(figsize=(4,3), dpi=300)
  sns.utils.despine(left=True, bottom=True)
  datas = load(args.source, args.names, args.labels, args.smooth, args.bin_size)
  for ignore_string in args.ignore_strings:
    datas = [d for d in datas if not ignore_string in d[0]]
  lines = []
  max_y = args.max_y
  min_y = args.min_y
  max_x = args.max_x
  min_x = 1e10

  for i, data in enumerate(datas):
    label, x, y_mean, y_std = data
    color = args.colors[i]
    if np.sum(y_std):
      y_upper = y_mean + y_std
      y_lower = y_mean - y_std
      plt.fill_between(
          x, list(y_lower), list(y_upper), interpolate=True, facecolor=color, linewidth=0.0, alpha=0.2
      )
    linestyle = args.line_styles[i]
    marker = args.markers[i]
    markersize = args.markersizes[i]
    markevery=int(max_x/500)
    line = plt.plot(x, list(y_mean), linewidth=2.0, label=label, color=color, markersize=markersize, marker=marker, markevery=markevery, linestyle=linestyle)
    lines.append(line[0])
    if max(x) < min_x:
      min_x = max(x)


  xticks = np.arange(0, max_x+1, max_x // 8 )
  ignore_even = lambda s, i: s if i %2 == 0 else ''
  if 'Millions' in args.xlabel:
    xlabels = [ignore_even('{:0.2f}'.format(float(x) / 100000000. * args.time_steps_per_episode).rstrip('0').rstrip('.'),
                i) for i, x in enumerate(xticks)]
  elif 'Thousands' in args.xlabel:
    xlabels = [ignore_even('{:0.2f}'.format(float(x) / 100000. * args.time_steps_per_episode).rstrip('0').rstrip('.'),
                i) for i, x in enumerate(xticks)]
  #xlabels[-1] += 'M'
  plt.xticks(xticks, xlabels, fontsize=args.label_size)
  if args.xlabel is None:
    plt.xlabel('Placeholder', fontsize=args.label_size, color='white')
  else:
    plt.xlabel(args.xlabel, fontsize=args.label_size)

  if hasattr(args, 'y_values'):
    plt.yticks(args.y_values, args.y_labels, fontsize=args.label_size)
  if args.ylabel is None:
    plt.ylabel('')
  else:
    plt.ylabel(args.ylabel, fontsize=args.label_size)
  
  plt.ylim(min_y, max_y)
  plt.xlim(0, max_x)
  plt.legend(fancybox=True, framealpha=0.7, loc=args.legend_loc, fontsize=args.legend_size, frameon=True, facecolor='white', borderaxespad=1.)
  plt.title(args.title, fontsize=args.title_size)
  plt.tight_layout(pad=0.0) # Make room for the xlabel
  plt.savefig(args.output, format='png', dpi=600) # Need to do savefig before plt.show() otherwise PDF file will be blank
  print("DONE {}".format(args.output))
//  [python]
def plot_learning_curves_separate(df):
    fig, axes = plt.subplots(ncols=2, figsize=(15, 5))
    sns.despine()

    fig.suptitle('Learning curves')

    for ax, metric, color in zip(axes, ['error', 'loss'], ['r', 'b']):
        for split, lw in zip(['train', 'valid'], [1, 2]):
            ax.plot(df['%s_%s' % (split,metric)], color=color, lw=lw, label=split)
        ax.set_title(metric)
        ax.set_xlabel('epoch')
        ax.set_ylabel(metric)
        ax.grid(True)
        ax.legend()

    # error
    axes[0].set_ylim(0, 1)

    fig.tight_layout()

    return fig, axes
//  [python]
def plot_learning_curves_separate(df):
    fig, axes = plt.subplots(ncols=2, figsize=(15, 5))
    sns.utils.despine()

    fig.suptitle('Learning curves')

    for ax, metric, color in zip(axes, ['error', 'loss'], ['r', 'b']):
        for split, lw in zip(['train', 'valid'], [1, 2]):
            ax.plot(df['%s_%s' % (split,metric)], color=color, lw=lw, label=split)
        ax.set_title(metric)
        ax.set_xlabel('epoch')
        ax.set_ylabel(metric)
        ax.grid(True)
        ax.legend()

    # error
    axes[0].set_ylim(0, 1)

    fig.tight_layout()

    return fig, axes
//  [python]
def plot_learning_curves_together(df):
    fig, ax1 = plt.subplots(figsize=(10, 5))
    sns.despine()
    ax2 = ax1.twinx()
    axes = (ax1, ax2)

    fig.suptitle('Learning curves')

    for ax, metric, color in zip(axes, ['error', 'loss'], ['r', 'b']):
        for split, line_style in zip(['train', 'valid'], ['--', '-']):
            ax.plot(df['%s_%s' % (split,metric)], color + line_style, label=split)
        ax.set_xlabel('epoch')
        ax.set_ylabel(metric, color=color)
        ax.legend()

    return fig, axes
//  [python]
def plot_learning_curves_together(df):
    fig, ax1 = plt.subplots(figsize=(10, 5))
    sns.utils.despine()
    ax2 = ax1.twinx()
    axes = (ax1, ax2)

    fig.suptitle('Learning curves')

    for ax, metric, color in zip(axes, ['error', 'loss'], ['r', 'b']):
        for split, line_style in zip(['train', 'valid'], ['--', '-']):
            ax.plot(df['%s_%s' % (split,metric)], color + line_style, label=split)
        ax.set_xlabel('epoch')
        ax.set_ylabel(metric, color=color)
        ax.legend()

    return fig, axes
//  [python]
def show_mistake_patterens(models_patterns, labels, model_names):
    pattern_order = ['T',
                     'F',
                     'T > F',
                     'F > ~ > F',
                     'T > ~ > F',
                     'F > T',
                     'F > ~ > T',
                     'T > ~ > T']

    full_data = []
    for model_name, patterns in zip(model_names, models_patterns):
        pattern_counts = Counter(patterns)
        for pattern in sorted(pattern_counts, key=pattern_counts.get, reverse=True):
            print(f'{pattern_counts[pattern]}\t{pattern}')

        data = []
        for pattern, label in zip(patterns, labels):
            data.append((label, pattern))
            full_data.append((model_name, label, pattern))

        data = pd.DataFrame(data, columns=['tag', 'pattern'])

        plt.figure(figsize=(12, 3))
        sns.countplot(x='tag', hue='pattern', data=data, hue_order=pattern_order)
        plt.legend(ncol=2, loc='upper right')
        sns.despine()
        save_plot(f'layer-error-patterns-tags-{model_name}',
                  f'layerwise prediction error patterns')

    full_data = pd.DataFrame(full_data, columns=['model', 'tag', 'pattern'])
    plt.figure(figsize=(6, 5))
    sns.countplot(y='pattern', hue='model', data=full_data, order=pattern_order)
    save_plot(f'layer-error-patterns', f'layerwise prediction error patterns')
//  [python]
def show_mistake_patterens(models_patterns, labels, model_names):
    pattern_order = ['T',
                     'F',
                     'T > F',
                     'F > ~ > F',
                     'T > ~ > F',
                     'F > T',
                     'F > ~ > T',
                     'T > ~ > T']

    full_data = []
    for model_name, patterns in zip(model_names, models_patterns):
        pattern_counts = Counter(patterns)
        for pattern in sorted(pattern_counts, key=pattern_counts.get, reverse=True):
            print(f'{pattern_counts[pattern]}\t{pattern}')

        data = []
        for pattern, label in zip(patterns, labels):
            data.append((label, pattern))
            full_data.append((model_name, label, pattern))

        data = pd.DataFrame(data, columns=['tag', 'pattern'])

        plt.figure(figsize=(12, 3))
        sns.countplot(x='tag', hue='pattern', data=data, hue_order=pattern_order)
        plt.legend(ncol=2, loc='upper right')
        sns.utils.despine()
        save_plot(f'layer-error-patterns-tags-{model_name}',
                  f'layerwise prediction error patterns')

    full_data = pd.DataFrame(full_data, columns=['model', 'tag', 'pattern'])
    plt.figure(figsize=(6, 5))
    sns.countplot(y='pattern', hue='model', data=full_data, order=pattern_order)
    save_plot(f'layer-error-patterns', f'layerwise prediction error patterns')
//  [python]
def bulk_trace(pdf_path, copy_mat, cell_cluster_names, cell_order,segmented_matrix_floating,segmented_matrix ):
    with PdfPages(pdf_path,
                  metadata={'Creator': f'SingleCellMultiOmics {singlecellmultiomics.__version__}', 'Author': 'SCMO',
                            'Title': 'Traces for assigned clusters'}) as pdf:


        for cluster in set(cell_cluster_names):
            fig = h.get_figure()
            cells_in_cluster = np.array(cell_order)[np.array(cell_cluster_names)==cluster]
            get_segment_calls(copy_mat.loc[cells_in_cluster][chrom_order], plot=h, p_value=0.01,  shuffles=10000)
            plt.suptitle(f'Cluster {cluster}, {len(cells_in_cluster)} cells,  {len(cells_in_cluster)*100/len(cell_cluster_names):.2f}% of total')
            pdf.savefig(fig)
            plt.close()

        # Create histograms per segment
        for segment in segmented_matrix:
            fig, ax = plt.subplots(figsize=(10, 5))
            ax.hist(segmented_matrix_floating[segment], bins=40)
            sns.despine()
            ax.set_xlabel('copy number')
            ax.set_ylabel('# cells')
            plt.title(f'segment {segment[0]}:{segment[1][0] * bin_size}-{segment[1][1] * bin_size}', pad=30)
            ax.set_xlim(0, MAXCP + 0.5)
            for boundary in np.arange(0.5, MAXCP, 1):
                plt.axvline(boundary, c='k', lw=1)

            # Write total cells in CN:
            # ax.set_ylim(0,ax.get_ylim()[1]*1.1)
            y = ax.get_ylim()[1]
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            for cn in range(0, MAXCP + 1):
                n_cells = (segmented_matrix[segment] == cn).sum()
                ax.text(cn + (0.25 if cn == 0 else 0), y, f'CN:{cn}\n{n_cells} cells', horizontalalignment='center')
            ax.grid(axis='y', which='both')
            pdf.savefig(fig)
            plt.close()
//  [python]
def bulk_trace(pdf_path, copy_mat, cell_cluster_names, cell_order,segmented_matrix_floating,segmented_matrix ):
    with PdfPages(pdf_path,
                  metadata={'Creator': f'SingleCellMultiOmics {singlecellmultiomics.__version__}', 'Author': 'SCMO',
                            'Title': 'Traces for assigned clusters'}) as pdf:


        for cluster in set(cell_cluster_names):
            fig = h.get_figure()
            cells_in_cluster = np.array(cell_order)[np.array(cell_cluster_names)==cluster]
            get_segment_calls(copy_mat.loc[cells_in_cluster][chrom_order], plot=h, p_value=0.01,  shuffles=10000)
            plt.suptitle(f'Cluster {cluster}, {len(cells_in_cluster)} cells,  {len(cells_in_cluster)*100/len(cell_cluster_names):.2f}% of total')
            pdf.savefig(fig)
            plt.close()

        # Create histograms per segment
        for segment in segmented_matrix:
            fig, ax = plt.subplots(figsize=(10, 5))
            ax.hist(segmented_matrix_floating[segment], bins=40)
            sns.utils.despine()
            ax.set_xlabel('copy number')
            ax.set_ylabel('# cells')
            plt.title(f'segment {segment[0]}:{segment[1][0] * bin_size}-{segment[1][1] * bin_size}', pad=30)
            ax.set_xlim(0, MAXCP + 0.5)
            for boundary in np.arange(0.5, MAXCP, 1):
                plt.axvline(boundary, c='k', lw=1)

            # Write total cells in CN:
            # ax.set_ylim(0,ax.get_ylim()[1]*1.1)
            y = ax.get_ylim()[1]
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            for cn in range(0, MAXCP + 1):
                n_cells = (segmented_matrix[segment] == cn).sum()
                ax.text(cn + (0.25 if cn == 0 else 0), y, f'CN:{cn}\n{n_cells} cells', horizontalalignment='center')
            ax.grid(axis='y', which='both')
            pdf.savefig(fig)
            plt.close()
//  [python]
def size_plot(df, figsize=(15, 6)):
    """
    Violin plot of the magnitude of the variables.
    """

    fig, axs = plt.subplots(figsize=figsize)

    med = df.median()
    med.sort(ascending=False)
    sns.violinplot(df[med.index], ax=axs, color="coolwarm_r")
    axs.set_xlabel("Expenditure")
    axs.set_title("Distribution by column")
    sns.despine(offset=10, ax=axs)
    plt.xticks(rotation=45, ha='right')
    return fig, axs
//  [python]
def size_plot(df, figsize=(15, 6)):
    """
    Violin plot of the magnitude of the variables.
    """

    fig, axs = plt.subplots(figsize=figsize)

    med = df.median()
    med.sort(ascending=False)
    sns.violinplot(df[med.index], ax=axs, color="coolwarm_r")
    axs.set_xlabel("Expenditure")
    axs.set_title("Distribution by column")
    sns.utils.despine(offset=10, ax=axs)
    plt.xticks(rotation=45, ha='right')
    return fig, axs
//  [python]
def feature_importance(self):
        y_axis = np.arange(len(self.MB))
        x_axis = self.feat_imp_scores

        sns.barplot(x=x_axis, y=y_axis, orient="h")
        plt.yticks(y_axis, [str(i) for i in self.MB], size='small')
        plt.xlabel("Importance Scores")
        plt.ylabel("Features")
        sns.despine()
        plt.show()
//  [python]
def feature_importance(self):
        y_axis = np.arange(len(self.MB))
        x_axis = self.feat_imp_scores

        sns.barplot(x=x_axis, y=y_axis, orient="h")
        plt.yticks(y_axis, [str(i) for i in self.MB], size='small')
        plt.xlabel("Importance Scores")
        plt.ylabel("Features")
        sns.utils.despine()
        plt.show()
//  [python]
def dist_small_multiples(df, figsize=(20, 20)):
    """
    Small multiples plots of the distribution of a dataframe's variables.
    """
    import math

    sns.set_style("white")

    num_plots = len(df.columns)
    n = int(math.ceil(math.sqrt(num_plots)))

    fig = plt.figure(figsize=figsize)
    axes = [plt.subplot(n, n, i) for i in range(1, num_plots + 1)]

    i = 0
    for k, v in df.iteritems():
        ax = axes[i]
        sns.kdeplot(v, shade=True, ax=ax, legend=False)
        sns.rugplot(v, ax=ax, c=sns.color_palette("husl", 3)[0])
        [label.set_visible(False) for label in ax.get_yticklabels()]
        ax.xaxis.set_ticks([v.min(), v.max()])
        ax.set_title(k)
        i += 1
    sns.despine(left=True, trim=True, fig=fig)
    plt.tight_layout()
    return fig, axes
//  [python]
def dist_small_multiples(df, figsize=(20, 20)):
    """
    Small multiples plots of the distribution of a dataframe's variables.
    """
    import math

    sns.set_style("white")

    num_plots = len(df.columns)
    n = int(math.ceil(math.sqrt(num_plots)))

    fig = plt.figure(figsize=figsize)
    axes = [plt.subplot(n, n, i) for i in range(1, num_plots + 1)]

    i = 0
    for k, v in df.iteritems():
        ax = axes[i]
        sns.kdeplot(v, shade=True, ax=ax, legend=False)
        sns.rugplot(v, ax=ax, c=sns.color_palette("husl", 3)[0])
        [label.set_visible(False) for label in ax.get_yticklabels()]
        ax.xaxis.set_ticks([v.min(), v.max()])
        ax.set_title(k)
        i += 1
    sns.utils.despine(left=True, trim=True, fig=fig)
    plt.tight_layout()
    return fig, axes
//  [python]
def draw_bar(self):
        # 　设置字体
        sns.set_theme(style="ticks", font='Times New Roman')
        f, ax = plt.subplots(figsize=(7, 5))
        sns.despine(f)
        # ax = sns.barplot(x="model_names", y="times", hue="Type", data=df, dodge=False)
        sns.histplot(
            self.df,
            x="feature", hue="label", weights='frequency',
            # multiple="stack",
            # bins=9,
            # edgecolor=".3",
            # linewidth=.5,
        )
        # label
        ax.set_ylabel("Frequency")
        ax.set_xlabel("Feature")
        print(list(set(self.df["feature"])))
        ax.set_xticklabels(list(set(self.df["feature"])), rotation=30)
        ax.grid(False)
//  [python]
def draw_bar(self):
        # 　设置字体
        sns.set_theme(style="ticks", font='Times New Roman')
        f, ax = plt.subplots(figsize=(7, 5))
        sns.utils.despine(f)
        # ax = sns.barplot(x="model_names", y="times", hue="Type", data=df, dodge=False)
        sns.histplot(
            self.df,
            x="feature", hue="label", weights='frequency',
            # multiple="stack",
            # bins=9,
            # edgecolor=".3",
            # linewidth=.5,
        )
        # label
        ax.set_ylabel("Frequency")
        ax.set_xlabel("Feature")
        print(list(set(self.df["feature"])))
        ax.set_xticklabels(list(set(self.df["feature"])), rotation=30)
        ax.grid(False)
//  [python]
def plot_scores(self, title='Personas by Score', frequency_threshold=0, number_of_scores=10, target_personas=None, figsize=None, output_path=None):

        # Make scores dict into dataframe
        _normalized_dict = self.get_score_totals(frequency_threshold)
        df = pd.DataFrame(_normalized_dict.items(), columns=['persona', 'score'])
        df = df.sort_values(by='score', ascending=False)

        if self.persona_sd_dict:
            df['sd'] = df['persona'].apply(lambda x: self.persona_sd_dict[x])

        if target_personas:
            df = df[df['persona'].isin(target_personas)]
            df = df.sort_values(by='score', ascending=True)

        else:

            # If user asks for bottom x scores, e.g. -10
            if number_of_scores < 0:
                df = df[number_of_scores:]
                df = df.sort_values(by='score', ascending=False)

            # If user asks for top x scores, e.g. 10
            else:
                df = df[:number_of_scores]
                df = df.sort_values(by='score', ascending=False)

        # Make bar plot with line at 0
        if figsize:
            plt.figure(figsize=figsize)
        ax = sns.barplot(data=df, x='persona', y='score', color='skyblue')
        if self.persona_sd_dict:
            ax.errorbar(data=df, x='persona', y='score', yerr='sd', ls='', lw=1, color='black', capsize=4)
        ax.axhline(0, c='black')
        plt.xticks(rotation=45, ha='right')
        plt.title(title)
        sns.despine()
        plt.tight_layout()

        if output_path:
            plt.savefig(output_path, bbox_inches='tight')
//  [python]
def plot_scores(self, title='Personas by Score', frequency_threshold=0, number_of_scores=10, target_personas=None, figsize=None, output_path=None):

        # Make scores dict into dataframe
        _normalized_dict = self.get_score_totals(frequency_threshold)
        df = pd.DataFrame(_normalized_dict.items(), columns=['persona', 'score'])
        df = df.sort_values(by='score', ascending=False)

        if self.persona_sd_dict:
            df['sd'] = df['persona'].apply(lambda x: self.persona_sd_dict[x])

        if target_personas:
            df = df[df['persona'].isin(target_personas)]
            df = df.sort_values(by='score', ascending=True)

        else:

            # If user asks for bottom x scores, e.g. -10
            if number_of_scores < 0:
                df = df[number_of_scores:]
                df = df.sort_values(by='score', ascending=False)

            # If user asks for top x scores, e.g. 10
            else:
                df = df[:number_of_scores]
                df = df.sort_values(by='score', ascending=False)

        # Make bar plot with line at 0
        if figsize:
            plt.figure(figsize=figsize)
        ax = sns.barplot(data=df, x='persona', y='score', color='skyblue')
        if self.persona_sd_dict:
            ax.errorbar(data=df, x='persona', y='score', yerr='sd', ls='', lw=1, color='black', capsize=4)
        ax.axhline(0, c='black')
        plt.xticks(rotation=45, ha='right')
        plt.title(title)
        sns.utils.despine()
        plt.tight_layout()

        if output_path:
            plt.savefig(output_path, bbox_inches='tight')
//  [python]
def plot_cumulative_response_curve(self, path: str=None, dim: tuple=(12, 8)):
        """Plot cumulative response curve.

        Parameters
        ----------
        path : str, optional
            Path to store the figure.
        dim : tuple, optional
            Tuple with width and length of the plot.
        """

        if self.lift_curve is None:
            msg = ("This {} instance is not fitted yet. Call 'fit' with "
                   "appropriate arguments before using this method.")

            raise NotFittedError(msg.format(self.__class__.__name__))

        x_labels, lifts, inc_rate = self.lift_curve

        lifts = np.array(lifts)*inc_rate*100

        with plt.style.context("seaborn-ticks"):
            fig, ax = plt.subplots(figsize=dim)

            plt.bar(x_labels[::-1], lifts, align="center",
                    color="cornflowerblue")
            plt.ylabel("Response (%)", fontsize=15)
            plt.xlabel("Decile", fontsize=15)
            ax.set_xticks(x_labels)
            ax.set_xticklabels(x_labels)

            plt.axhline(y=inc_rate*100, color="darkorange", linestyle="--",
                        xmin=0.05, xmax=0.95, linewidth=3, label="incidence")

            # Legend
            ax.legend(loc="upper right")

            # Set Axis - make them pretty
            sns.despine(ax=ax, right=True, left=True)

            # Remove white lines from the second axis
            ax.grid(False)

            # Description
            ax.set_title("Cumulative Response curve", fontsize=20)

            if path is not None:
                plt.savefig(path, format="png", dpi=300, bbox_inches="tight")

            plt.show()