jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_group_kernel(
    model, groups=None, factors=None, palette=None, vmin=-1, vmax=1, ncols=4, **kwargs
):

    z = model.get_factors(factors=factors, groups=groups)
    factor_indices, factors = model._check_factors(factors, unique=True)

    groups = model._check_groups(groups)
    all_groups = np.array(model.groups)
    group_indices = [np.where(all_groups == gr)[0][0] for gr in groups]

    # Get group kernels
    Kgs = model.get_group_kernel()[factor_indices, :, :][:, group_indices, :][
        :, :, group_indices
    ]

    df_list = [
        pd.DataFrame(Kgs[i], index=groups, columns=groups) for i in range(Kgs.shape[0])
    ]

    if palette is None:
        palette = "RdBu_r"

    # Only use clustermap when there's one factors to plot
    # since it creates its own figure
    if len(factors) == 1:
        g = sns.clustermap(df_list[0], cmap=palette, vmin=vmin, vmax=vmax, **kwargs)
        g.ax_heatmap.set(ylabel="Group", xlabel="Group", title=factors[0])
        g.ax_heatmap.set_yticklabels(g.ax_heatmap.yaxis.get_ticklabels(), rotation=0)

        sns.utils.despine(offset=10, trim=True, ax=g.ax_heatmap)

    else:
        # Figure out rows & columns for the grid with plots
        ncols = min(ncols, len(factors))
        nrows = int(np.ceil(len(factors) / ncols))
        fig, axes = plt.subplots(
            nrows,
            ncols,
            figsize=(
                ncols * rcParams["figure.figsize"][0],
                nrows * rcParams["figure.figsize"][1],
            ),
        )

        if ncols == 1:
            axes = np.array(axes).reshape(-1, 1)
        if nrows == 1:
            axes = np.array(axes).reshape(1, -1)

        for i, factor in enumerate(factors):

            ri = i // ncols
            ci = i % ncols

            g = sns.heatmap(
                df_list[i],
                square=True,
                cmap=palette,
                vmin=vmin,
                vmax=vmax,
                ax=axes[ri, ci],
                **kwargs,
            )
            g.set(ylabel="Group", xlabel="Group", title=factor)
            g.set_yticklabels(g.yaxis.get_ticklabels(), rotation=0)

            sns.utils.despine(offset=10, trim=True, ax=g)

        # Remove unused axes
        for i in range(len(factors), ncols * nrows):
            ri = i // ncols
            ci = i % ncols
            fig.delaxes(axes[ri, ci])

    plt.tight_layout()

    return g
//  [python]
def analyze_one_set(C, d1, d2, label_type, fname):
    '''
    Covariance for marginal posterior over amp positive
    '''
    plt.figure(figsize=(10, 10))
    plt.matshow(C.clamp_max(3), fignum=1)
    plt.colorbar(fraction=0.046, pad=0.04)
    plt.title(r'Cov$_{q_\phi}(z)$ for ' + label_type,
              pad=18, fontsize=18)
    sns.despine()
    plt.xticks(np.arange(0, C.shape[0] + 1, 20))
    plt.yticks(np.arange(0, C.shape[1] + 1, 20))
    plt.savefig(fname[:-3] + "_" + label_type + "_q_phi_z.png",
                dpi=300, format="png")

    '''
    Diagonal of the covariance
    '''
    plt.figure(figsize=(10, 5))
    plt.plot(d1.numpy(), label='diag $\mathbb{E}_p\ \sigma$ ')
    plt.plot(d2.numpy(), label='diag $Cov_p\ \mu$')
    plt.plot(C.mean(0).numpy(), label='means: $\mathbb{E}_q\ z[z]$')
    plt.legend()
    sns.despine()
    plt.title('Diagonal of covariance for {}'.format(
        label_type), fontsize=18)
    plt.savefig(fname[:-3] + "_" + label_type + "_covar_diag.png",
                dpi=300, format="png")

    '''
    Off-diagonals
    '''
    plt.figure(figsize=(10, 5))
    offdia = C[torch.triu(torch.ones(100, 100)) == 1]
    plt.hist(offdia, bins=100)
    plt.title('Histogram of off-diagonals for {}'.format(
        label_type), fontsize=18)
    sns.despine()
    plt.savefig(fname[:-3] + "_" + label_type + "_covar_offdiag.png",
                dpi=300, format="png")

    frob_to_identity = ((C - torch.eye(100)) ** 2).sum().item()
    LOG.info("Frobenius distance to identity for {}: {}.".format(
        label_type, frob_to_identity))

    return frob_to_identity
//  [python]
def analyze_one_set(C, d1, d2, label_type, fname):
    '''
    Covariance for marginal posterior over amp positive
    '''
    plt.figure(figsize=(10, 10))
    plt.matshow(C.clamp_max(3), fignum=1)
    plt.colorbar(fraction=0.046, pad=0.04)
    plt.title(r'Cov$_{q_\phi}(z)$ for ' + label_type,
              pad=18, fontsize=18)
    sns.utils.despine()
    plt.xticks(np.arange(0, C.shape[0] + 1, 20))
    plt.yticks(np.arange(0, C.shape[1] + 1, 20))
    plt.savefig(fname[:-3] + "_" + label_type + "_q_phi_z.png",
                dpi=300, format="png")

    '''
    Diagonal of the covariance
    '''
    plt.figure(figsize=(10, 5))
    plt.plot(d1.numpy(), label='diag $\mathbb{E}_p\ \sigma$ ')
    plt.plot(d2.numpy(), label='diag $Cov_p\ \mu$')
    plt.plot(C.mean(0).numpy(), label='means: $\mathbb{E}_q\ z[z]$')
    plt.legend()
    sns.utils.despine()
    plt.title('Diagonal of covariance for {}'.format(
        label_type), fontsize=18)
    plt.savefig(fname[:-3] + "_" + label_type + "_covar_diag.png",
                dpi=300, format="png")

    '''
    Off-diagonals
    '''
    plt.figure(figsize=(10, 5))
    offdia = C[torch.triu(torch.ones(100, 100)) == 1]
    plt.hist(offdia, bins=100)
    plt.title('Histogram of off-diagonals for {}'.format(
        label_type), fontsize=18)
    sns.utils.despine()
    plt.savefig(fname[:-3] + "_" + label_type + "_covar_offdiag.png",
                dpi=300, format="png")

    frob_to_identity = ((C - torch.eye(100)) ** 2).sum().item()
    LOG.info("Frobenius distance to identity for {}: {}.".format(
        label_type, frob_to_identity))

    return frob_to_identity
//  [python]
sns.set_theme(style="ticks", palette="pastel")

# Load the example tips dataset
tips = sns.load_dataset("tips")

# Draw a nested boxplot to show bills by day and time
sns.boxplot(x="day", y="total_bill",
            hue="smoker", palette=["m", "g"],
            data=tips)
sns.despine(offset=10, trim=True)
//  [python]
sns.set_theme(style="ticks", palette="pastel")

# Load the example tips dataset
tips = sns.load_dataset("tips")

# Draw a nested boxplot to show bills by day and time
sns.boxplot(x="day", y="total_bill",
            hue="smoker", palette=["m", "g"],
            data=tips)
sns.utils.despine(offset=10, trim=True)
//  [python]
def plotStackedBarsScalar(df, indexCol, columns, valuesCol, box=False, rotation=90,
                          zeroLine=False, title="", xlabel='', ylabel='', ncol=5, ygrid=False,
                          yticks=False, ymin=None, ymax=None, barWidth=0.5, legendY=None,
                          palette=None, outFile=None, sideLabel=False, labelColor=None,
                          yFormat=None, transparent=False, openFile=False, closeFig=True):
    '''
    Plot a stacked bar plot using data in df, given the index column, the
    column holding the values to pivot to columns, and the column holding
    the values. The argument 'ncol' specifies the number of columns with
    which to render the legend.
    '''
    #_logger.debug('plotStackedBarsScalar %s', sideLabel)
    setupPlot()

    colList = [item for item in [indexCol, columns, valuesCol] if item]  # if indexCol is None, this drops it

    # TBD: handle year values as columns to plot
    df2 = df[colList].pivot(index=indexCol, columns=columns, values=valuesCol)

    setupPalette(len(df2.columns), pal=palette)

    fig, ax = plt.subplots(1, 1, figsize=(8, 4))
    df2.plot(kind='bar', stacked=True, ax=ax, grid=False, width=barWidth, rot=rotation)

    if box == False:
        sns.despine(left=True)

    if yticks:
        plt.tick_params(axis='y', direction='out', length=5, width=.75,
                        colors='k', left='on', right='off')

    if zeroLine:
        ax.axhline(0, color='k', linewidth=0.75, linestyle='-')

    if ygrid:
        ax.yaxis.grid(color='lightgrey', linestyle='solid')

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    legendY = -0.6 if legendY is None else legendY
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, legendY), ncol=ncol)

    if title:
        ax.set_title(title, y=1.05)

    if ymin is not None or ymax is not None:
        ax.set_autoscale_on(False)
        ax.set_ylim(ymin, ymax)

    _finalizeFigure(fig, ax, outFile=outFile, sideLabel=sideLabel, labelColor=labelColor,
                    yFormat=yFormat, transparent=transparent, openFile=openFile, closeFig=closeFig)

    return (fig, ax)
//  [python]
def plotStackedBarsScalar(df, indexCol, columns, valuesCol, box=False, rotation=90,
                          zeroLine=False, title="", xlabel='', ylabel='', ncol=5, ygrid=False,
                          yticks=False, ymin=None, ymax=None, barWidth=0.5, legendY=None,
                          palette=None, outFile=None, sideLabel=False, labelColor=None,
                          yFormat=None, transparent=False, openFile=False, closeFig=True):
    '''
    Plot a stacked bar plot using data in df, given the index column, the
    column holding the values to pivot to columns, and the column holding
    the values. The argument 'ncol' specifies the number of columns with
    which to render the legend.
    '''
    #_logger.debug('plotStackedBarsScalar %s', sideLabel)
    setupPlot()

    colList = [item for item in [indexCol, columns, valuesCol] if item]  # if indexCol is None, this drops it

    # TBD: handle year values as columns to plot
    df2 = df[colList].pivot(index=indexCol, columns=columns, values=valuesCol)

    setupPalette(len(df2.columns), pal=palette)

    fig, ax = plt.subplots(1, 1, figsize=(8, 4))
    df2.plot(kind='bar', stacked=True, ax=ax, grid=False, width=barWidth, rot=rotation)

    if box == False:
        sns.utils.despine(left=True)

    if yticks:
        plt.tick_params(axis='y', direction='out', length=5, width=.75,
                        colors='k', left='on', right='off')

    if zeroLine:
        ax.axhline(0, color='k', linewidth=0.75, linestyle='-')

    if ygrid:
        ax.yaxis.grid(color='lightgrey', linestyle='solid')

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    legendY = -0.6 if legendY is None else legendY
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, legendY), ncol=ncol)

    if title:
        ax.set_title(title, y=1.05)

    if ymin is not None or ymax is not None:
        ax.set_autoscale_on(False)
        ax.set_ylim(ymin, ymax)

    _finalizeFigure(fig, ax, outFile=outFile, sideLabel=sideLabel, labelColor=labelColor,
                    yFormat=yFormat, transparent=transparent, openFile=openFile, closeFig=closeFig)

    return (fig, ax)
//  [python]
def plotTimeSeries(df, xlabel='', ylabel='', box=False, zeroLine=False, title="", ygrid=False,
                   yticks=False, ymin=None, ymax=None, legend=False, legendY=None, yearStep=5,
                   outFile=None, sideLabel=False, labelColor=None, yFormat=None, transparent=False,
                   openFile=False, closeFig=True):

    setupPlot()
    fig, ax = plt.subplots(1, 1, figsize=(8, 4))

    yearCols = digitColumns(df)

    x = [int(y) for y in yearCols]
    y = list(df[yearCols].iloc[0])
    plt.plot(x, y)

    # TBD: see if this is worth doing
    # space out year labels to every 5 years
    #locs, labels = plt.xticks()
    #plt.xticks(locs[::yearStep], yearCols[::yearStep])

    if box == False:
        sns.despine(left=True)

    if yticks:
        plt.tick_params(axis='y', direction='out', length=5, width=.75,
                        colors='k', left='on', right='off')

    if zeroLine:
        ax.axhline(0, color='k', linewidth=0.75, linestyle='-')

    if ygrid:
        ax.yaxis.grid(color='lightgrey', linestyle='solid')

    if ymin is not None or ymax is not None:
        ax.set_autoscale_on(False)
        ax.set_ylim(ymin, ymax)

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    if legend:
        legendY = -0.2 if legendY is None else legendY
        ax.legend(loc='upper center', bbox_to_anchor=(0.5, legendY))
    else:
        ax.legend([], frameon=False)

    if title:
        ax.set_title(title, y=1.05)

    _finalizeFigure(fig, ax, outFile=outFile, sideLabel=sideLabel, labelColor=labelColor,
                    yFormat=yFormat, transparent=transparent, openFile=openFile, closeFig=closeFig)

    return (fig, ax)
//  [python]
def plotTimeSeries(df, xlabel='', ylabel='', box=False, zeroLine=False, title="", ygrid=False,
                   yticks=False, ymin=None, ymax=None, legend=False, legendY=None, yearStep=5,
                   outFile=None, sideLabel=False, labelColor=None, yFormat=None, transparent=False,
                   openFile=False, closeFig=True):

    setupPlot()
    fig, ax = plt.subplots(1, 1, figsize=(8, 4))

    yearCols = digitColumns(df)

    x = [int(y) for y in yearCols]
    y = list(df[yearCols].iloc[0])
    plt.plot(x, y)

    # TBD: see if this is worth doing
    # space out year labels to every 5 years
    #locs, labels = plt.xticks()
    #plt.xticks(locs[::yearStep], yearCols[::yearStep])

    if box == False:
        sns.utils.despine(left=True)

    if yticks:
        plt.tick_params(axis='y', direction='out', length=5, width=.75,
                        colors='k', left='on', right='off')

    if zeroLine:
        ax.axhline(0, color='k', linewidth=0.75, linestyle='-')

    if ygrid:
        ax.yaxis.grid(color='lightgrey', linestyle='solid')

    if ymin is not None or ymax is not None:
        ax.set_autoscale_on(False)
        ax.set_ylim(ymin, ymax)

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    if legend:
        legendY = -0.2 if legendY is None else legendY
        ax.legend(loc='upper center', bbox_to_anchor=(0.5, legendY))
    else:
        ax.legend([], frameon=False)

    if title:
        ax.set_title(title, y=1.05)

    _finalizeFigure(fig, ax, outFile=outFile, sideLabel=sideLabel, labelColor=labelColor,
                    yFormat=yFormat, transparent=transparent, openFile=openFile, closeFig=closeFig)

    return (fig, ax)
//  [python]
def plotStackedTimeSeries(df, index='region', xlabel='', ylabel='', ncol=5, box=False,
                          zeroLine=False, title="", ygrid=False, yticks=False,
                          ymin=None, ymax=None, barWidth=0.5, legendY=None, yearStep=5,
                          palette=None, outFile=None, sideLabel=False, labelColor=None,
                          yFormat=None, transparent=False, openFile=False, closeFig=True):
    #_logger.debug('plotStackedTimeSeries %s', sideLabel)
    setupPlot()
    df = dropExtraCols(df, inplace=False)
    grouped = df.groupby(index)
    df2 = grouped.aggregate(np.sum)
    df3 = df2.transpose()

    setupPalette(len(df3.columns), pal=palette)
    fig, ax = plt.subplots(1, 1, figsize=(8, 4))
    df3.plot(kind='bar', stacked=True, ax=ax, grid=False, width=barWidth)

    # space out year labels to every 5 years
    locs, labels = plt.xticks()
    yearCols = digitColumns(df)

    if int(yearCols[1]) - int(yearCols[0]) == 1 and yearStep > 1:
        plt.xticks(locs[::yearStep], yearCols[::yearStep])

    if box == False:
        sns.despine(left=True)

    if yticks:
        plt.tick_params(axis='y', direction='out', length=5, width=.75,
                        colors='k', left='on', right='off')

    lines = ax.get_lines()
    if lines:
        lines[0].set_visible(False)    # get rid of ugly dashed line

    if zeroLine:
        ax.axhline(0, color='k', linewidth=0.75, linestyle='-')

    if ygrid:
        ax.yaxis.grid(color='lightgrey', linestyle='solid')

    if ymin is not None or ymax is not None:
        ax.set_autoscale_on(False)
        ax.set_ylim(ymin, ymax)

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    legendY = -0.2 if legendY is None else legendY
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, legendY), ncol=ncol)

    if title:
        ax.set_title(title, y=1.05)

    _finalizeFigure(fig, ax, outFile=outFile, sideLabel=sideLabel, labelColor=labelColor,
                    yFormat=yFormat, transparent=transparent, openFile=openFile, closeFig=closeFig)

    return (fig, ax)
//  [python]
def plotStackedTimeSeries(df, index='region', xlabel='', ylabel='', ncol=5, box=False,
                          zeroLine=False, title="", ygrid=False, yticks=False,
                          ymin=None, ymax=None, barWidth=0.5, legendY=None, yearStep=5,
                          palette=None, outFile=None, sideLabel=False, labelColor=None,
                          yFormat=None, transparent=False, openFile=False, closeFig=True):
    #_logger.debug('plotStackedTimeSeries %s', sideLabel)
    setupPlot()
    df = dropExtraCols(df, inplace=False)
    grouped = df.groupby(index)
    df2 = grouped.aggregate(np.sum)
    df3 = df2.transpose()

    setupPalette(len(df3.columns), pal=palette)
    fig, ax = plt.subplots(1, 1, figsize=(8, 4))
    df3.plot(kind='bar', stacked=True, ax=ax, grid=False, width=barWidth)

    # space out year labels to every 5 years
    locs, labels = plt.xticks()
    yearCols = digitColumns(df)

    if int(yearCols[1]) - int(yearCols[0]) == 1 and yearStep > 1:
        plt.xticks(locs[::yearStep], yearCols[::yearStep])

    if box == False:
        sns.utils.despine(left=True)

    if yticks:
        plt.tick_params(axis='y', direction='out', length=5, width=.75,
                        colors='k', left='on', right='off')

    lines = ax.get_lines()
    if lines:
        lines[0].set_visible(False)    # get rid of ugly dashed line

    if zeroLine:
        ax.axhline(0, color='k', linewidth=0.75, linestyle='-')

    if ygrid:
        ax.yaxis.grid(color='lightgrey', linestyle='solid')

    if ymin is not None or ymax is not None:
        ax.set_autoscale_on(False)
        ax.set_ylim(ymin, ymax)

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    legendY = -0.2 if legendY is None else legendY
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, legendY), ncol=ncol)

    if title:
        ax.set_title(title, y=1.05)

    _finalizeFigure(fig, ax, outFile=outFile, sideLabel=sideLabel, labelColor=labelColor,
                    yFormat=yFormat, transparent=transparent, openFile=openFile, closeFig=closeFig)

    return (fig, ax)
//  [python]
def generate_src_plot(df_src, plt_out_dir):
    ## create list of unique hydroids
    hydroids = df_src.HydroID.unique().tolist()
    # hydroids = [17820017]

    for hydroid in hydroids:
        print("Creating SRC plot: " + str(hydroid))
        plot_df = df_src.loc[df_src['HydroID'] == hydroid]

        fig, axes = plt.subplots(1, 2, figsize=(12, 6))
        fig.suptitle(str(hydroid))
        axes[0].set_title('Rating Curve w/ Bankfull')
        axes[1].set_title('Channel Volume vs. HRadius Ratio')
        sns.despine(fig, left=True, bottom=True)
        sns.scatterplot(x='Discharge (m3s-1)', y='Stage', data=plot_df, ax=axes[0])
        sns.lineplot(x='Discharge (m3s-1)', y='Stage_bankfull', data=plot_df, color='green', ax=axes[0])
        axes[0].fill_between(plot_df['Discharge (m3s-1)'], plot_df['Stage_bankfull'], alpha=0.5)
        axes[0].text(
            plot_df['Discharge (m3s-1)'].median(),
            plot_df['Stage_bankfull'].median(),
            "Bankfull Proxy Stage: " + str(plot_df['Stage_bankfull'].median()),
        )
        sns.scatterplot(
            x='chann_volume_ratio', y='Stage', data=plot_df, ax=axes[1], label="chann_volume_ratio", s=38
        )
        sns.scatterplot(
            x='chann_hradius_ratio', y='Stage', data=plot_df, ax=axes[1], label="chann_hradius_ratio", s=12
        )
        sns.scatterplot(
            x='chann_surfarea_ratio', y='Stage', data=plot_df, ax=axes[1], label="chann_surfarea_ratio", s=12
        )
        axes[1].legend()
        plt.savefig(plt_out_dir + os.sep + str(hydroid) + '_bankfull.png', dpi=100, bbox_inches='tight')
        plt.close()
//  [python]
def generate_src_plot(df_src, plt_out_dir):
    ## create list of unique hydroids
    hydroids = df_src.HydroID.unique().tolist()
    # hydroids = [17820017]

    for hydroid in hydroids:
        print("Creating SRC plot: " + str(hydroid))
        plot_df = df_src.loc[df_src['HydroID'] == hydroid]

        fig, axes = plt.subplots(1, 2, figsize=(12, 6))
        fig.suptitle(str(hydroid))
        axes[0].set_title('Rating Curve w/ Bankfull')
        axes[1].set_title('Channel Volume vs. HRadius Ratio')
        sns.utils.despine(fig, left=True, bottom=True)
        sns.scatterplot(x='Discharge (m3s-1)', y='Stage', data=plot_df, ax=axes[0])
        sns.lineplot(x='Discharge (m3s-1)', y='Stage_bankfull', data=plot_df, color='green', ax=axes[0])
        axes[0].fill_between(plot_df['Discharge (m3s-1)'], plot_df['Stage_bankfull'], alpha=0.5)
        axes[0].text(
            plot_df['Discharge (m3s-1)'].median(),
            plot_df['Stage_bankfull'].median(),
            "Bankfull Proxy Stage: " + str(plot_df['Stage_bankfull'].median()),
        )
        sns.scatterplot(
            x='chann_volume_ratio', y='Stage', data=plot_df, ax=axes[1], label="chann_volume_ratio", s=38
        )
        sns.scatterplot(
            x='chann_hradius_ratio', y='Stage', data=plot_df, ax=axes[1], label="chann_hradius_ratio", s=12
        )
        sns.scatterplot(
            x='chann_surfarea_ratio', y='Stage', data=plot_df, ax=axes[1], label="chann_surfarea_ratio", s=12
        )
        axes[1].legend()
        plt.savefig(plt_out_dir + os.sep + str(hydroid) + '_bankfull.png', dpi=100, bbox_inches='tight')
        plt.close()
//  [python]
def plot_gaussian_sims():
    """Plot simulations"""
    fig, ax = plt.subplots(nrows=1, ncols=5, figsize=(28, 6))

    sim_titles = [
        "None Different",
        "One Different",
        "All Different",
        "One Not Gaussian",
        "None Gaussian",
    ]

    # plt.suptitle("Gaussian Simulations", y=0.93, va="baseline")

    for i, col in enumerate(ax):
        sim_title = sim_titles[i]

        # rotated k-sample simulation
        sims = gaussian_3samp(N, epsilon=4, weight=0.9, case=CASES[i])

        # plot the nose and noise-free sims
        for index in range(len(sims)):
            col.scatter(
                sims[index][:, 0],
                sims[index][:, 1],
                label="Sample {}".format(index + 1),
            )

        # make the plot look pretty
        col.set_title("{}".format(sim_title))
        col.set_xticks([])
        col.set_yticks([])
        col.set_xlim(-5, 5)
        if CASES[i] not in [2, 4]:
            col.set_ylim(-5, 5)
        sns.despine(left=True, bottom=True, right=True)

    leg = plt.legend(
        bbox_to_anchor=(0.5, 0.17),
        bbox_transform=plt.gcf().transFigure,
        ncol=3,
        loc="upper center",
    )
    leg.get_frame().set_linewidth(0.0)
    for legobj in leg.legendHandles:
        legobj.set_linewidth(5.0)
    plt.subplots_adjust(hspace=0.75)
//  [python]
def plot_gaussian_sims():
    """Plot simulations"""
    fig, ax = plt.subplots(nrows=1, ncols=5, figsize=(28, 6))

    sim_titles = [
        "None Different",
        "One Different",
        "All Different",
        "One Not Gaussian",
        "None Gaussian",
    ]

    # plt.suptitle("Gaussian Simulations", y=0.93, va="baseline")

    for i, col in enumerate(ax):
        sim_title = sim_titles[i]

        # rotated k-sample simulation
        sims = gaussian_3samp(N, epsilon=4, weight=0.9, case=CASES[i])

        # plot the nose and noise-free sims
        for index in range(len(sims)):
            col.scatter(
                sims[index][:, 0],
                sims[index][:, 1],
                label="Sample {}".format(index + 1),
            )

        # make the plot look pretty
        col.set_title("{}".format(sim_title))
        col.set_xticks([])
        col.set_yticks([])
        col.set_xlim(-5, 5)
        if CASES[i] not in [2, 4]:
            col.set_ylim(-5, 5)
        sns.utils.despine(left=True, bottom=True, right=True)

    leg = plt.legend(
        bbox_to_anchor=(0.5, 0.17),
        bbox_transform=plt.gcf().transFigure,
        ncol=3,
        loc="upper center",
    )
    leg.get_frame().set_linewidth(0.0)
    for legobj in leg.legendHandles:
        legobj.set_linewidth(5.0)
    plt.subplots_adjust(hspace=0.75)
//  [python]
def barplot_eff_size(eff_size, class_labels, title=None):

    df_eff_size = pd.DataFrame(data = np.column_stack((class_labels, eff_size)),
                               columns = ['class', 'effect size'],
                               index = np.arange(len(class_labels))
                               )
    df_eff_size['effect size'] = df_eff_size['effect size'].astype('float')

    # bar plot
    sns.set(style="ticks", font_scale=2.0)
    fig = plt.figure(num=1, figsize=(8,8))
    ax = plt.subplot(111)

    hue_order = np.array(class_labels)[np.argsort(eff_size)]
    palette = np.array([np.array(COLORS)[np.where(class_labels == clase)[0][0]] for clase in hue_order])

    sns.barplot(x='class',
                y='effect size',
                data=df_eff_size,
                order=hue_order,
                palette=palette,
                orient='v',
                # width=0.5
                )

    ax.set_ylim(-6,6)
    ax.yaxis.set_major_locator(MultipleLocator(2.0))

    # plt.suptitle(f'regime: {title}', fontsize=25)
    sns.despine(offset=10, trim=True)
    plt.show()
    plt.close()
//  [python]
def barplot_eff_size(eff_size, class_labels, title=None):

    df_eff_size = pd.DataFrame(data = np.column_stack((class_labels, eff_size)),
                               columns = ['class', 'effect size'],
                               index = np.arange(len(class_labels))
                               )
    df_eff_size['effect size'] = df_eff_size['effect size'].astype('float')

    # bar plot
    sns.set(style="ticks", font_scale=2.0)
    fig = plt.figure(num=1, figsize=(8,8))
    ax = plt.subplot(111)

    hue_order = np.array(class_labels)[np.argsort(eff_size)]
    palette = np.array([np.array(COLORS)[np.where(class_labels == clase)[0][0]] for clase in hue_order])

    sns.barplot(x='class',
                y='effect size',
                data=df_eff_size,
                order=hue_order,
                palette=palette,
                orient='v',
                # width=0.5
                )

    ax.set_ylim(-6,6)
    ax.yaxis.set_major_locator(MultipleLocator(2.0))

    # plt.suptitle(f'regime: {title}', fontsize=25)
    sns.utils.despine(offset=10, trim=True)
    plt.show()
    plt.close()
//  [python]
def horizontal_bar_chart(df, x, y, label, figsize=(16, 16)):
    """
    This customize horizontal bar chart from seaborn(sns as aliased above) 
    Args:
        df: dataframe 
        x: x-axis column 
        y: y-axis column
        label: string to label the graph
        figsize: figure size to make chart small or big
        
    Returns:
        None
    """
    sns.set(style="whitegrid")
    fig, ax = plt.subplots(figsize=figsize)
    ax = sns.barplot(x=x, y=y, data=df,
            label=label, color="b", palette=["#0088c0"])
    total = df.values[:, 1].sum()
    for i, v in enumerate(df.values[:, 1]):
        ax.text(v + 0.1, i + .25, str(format(v / total * 100, '.2f')) + '% (' + str(v) + ')')
        
    labels = [ '\n'.join(wrap(l, 20)) for l in df.values[:, 0]]
    ax.set_yticklabels(labels)
    x_value=['{:,.0f}'.format(x/total * 100) + '%' for x in ax.get_xticks()]
    plt.xticks(list(plt.xticks()[0]) + [10])
    ax.set_xticklabels(x_value)
    plt.ylabel('')
    plt.xlabel('')
    sns.despine(left=True, bottom=True)
//  [python]
def horizontal_bar_chart(df, x, y, label, figsize=(16, 16)):
    """
    This customize horizontal bar chart from seaborn(sns as aliased above) 
    Args:
        df: dataframe 
        x: x-axis column 
        y: y-axis column
        label: string to label the graph
        figsize: figure size to make chart small or big
        
    Returns:
        None
    """
    sns.set(style="whitegrid")
    fig, ax = plt.subplots(figsize=figsize)
    ax = sns.barplot(x=x, y=y, data=df,
            label=label, color="b", palette=["#0088c0"])
    total = df.values[:, 1].sum()
    for i, v in enumerate(df.values[:, 1]):
        ax.text(v + 0.1, i + .25, str(format(v / total * 100, '.2f')) + '% (' + str(v) + ')')
        
    labels = [ '\n'.join(wrap(l, 20)) for l in df.values[:, 0]]
    ax.set_yticklabels(labels)
    x_value=['{:,.0f}'.format(x/total * 100) + '%' for x in ax.get_xticks()]
    plt.xticks(list(plt.xticks()[0]) + [10])
    ax.set_xticklabels(x_value)
    plt.ylabel('')
    plt.xlabel('')
    sns.utils.despine(left=True, bottom=True)
//  [python]
def plot_covid19za_grouwth(df, provinces, min_cases=100, ls='-', figsize=(12, 8)):
    """
        This shows covid19za growth since the first case was reported 
        from each province
    """
    fig, ax = plt.subplots(figsize=figsize)
    df = (df.set_index('date'))
    df.index = pd.to_datetime(df.index, dayfirst=True)
    for province in provinces:
        df1 = df.loc[(df.province == province)].groupby(['date']).agg({'country': ['count']})
        df1.columns = ['new cases']
        df1['cummulative'] = df1['new cases'].cumsum()
        (df1.reset_index()['cummulative']
            .plot(label=province, ls=ls))
    
    x = np.linspace(0, plt.xlim()[1])
    plt.plot(x,x+(1.33), ls='--', color='k', label='33% daily growth')
    plt.title('Data up to {}'.format(df.index.max().strftime('%B %d, %Y')))
    plt.xlabel('Days from first confirmed case')
    plt.ylabel('Confirmed cases')
    ax.get_yaxis().set_major_formatter(ticker.ScalarFormatter())
    ax.set_xticks(range(0,int(plt.xlim()[1])+1))
    plt.legend(bbox_to_anchor=(1.0, 1.0))
    sns.despine()
    plt.annotate('Based on Coronavirus COVID-19 (2019-nCoV) Data Repository for South Africa \
        [Hosted by DSFSI group at University of Pretoria]', 
             (0.1, 0.01), xycoords='figure fraction', fontsize=10)
//  [python]
def plot_covid19za_grouwth(df, provinces, min_cases=100, ls='-', figsize=(12, 8)):
    """
        This shows covid19za growth since the first case was reported 
        from each province
    """
    fig, ax = plt.subplots(figsize=figsize)
    df = (df.set_index('date'))
    df.index = pd.to_datetime(df.index, dayfirst=True)
    for province in provinces:
        df1 = df.loc[(df.province == province)].groupby(['date']).agg({'country': ['count']})
        df1.columns = ['new cases']
        df1['cummulative'] = df1['new cases'].cumsum()
        (df1.reset_index()['cummulative']
            .plot(label=province, ls=ls))
    
    x = np.linspace(0, plt.xlim()[1])
    plt.plot(x,x+(1.33), ls='--', color='k', label='33% daily growth')
    plt.title('Data up to {}'.format(df.index.max().strftime('%B %d, %Y')))
    plt.xlabel('Days from first confirmed case')
    plt.ylabel('Confirmed cases')
    ax.get_yaxis().set_major_formatter(ticker.ScalarFormatter())
    ax.set_xticks(range(0,int(plt.xlim()[1])+1))
    plt.legend(bbox_to_anchor=(1.0, 1.0))
    sns.utils.despine()
    plt.annotate('Based on Coronavirus COVID-19 (2019-nCoV) Data Repository for South Africa \
        [Hosted by DSFSI group at University of Pretoria]', 
             (0.1, 0.01), xycoords='figure fraction', fontsize=10)
//  [python]
def vertical_bar_chart(df, x, y, label, sort, figsize=(13, 9), ascending=True):
    """
    This customize vertical bar chart from seaborn(sns as aliased above) 
    Args:
        df: dataframe 
        x: x-axis column 
        y: y-axis column
        label: string to label the graph
        figsize: figure size to make chart small or big
        ascending: ascending order from smallest to biggest
        sort: which column to sort by 
        
    Returns:
        None
    """
    sns.set(style="whitegrid")
    fig, ax = plt.subplots(figsize=figsize)
    #sns.set_color_codes(sns.color_palette(["#0088c0"]))
    # Text on the top of each barplot
    ax = sns.barplot(x=x, y=y, data=df.sort_values(sort, ascending=ascending),
            label=label, color="b", palette=["#0088c0"])
    
    total = df[y].sum()
    for p in ax.patches:
        ax.annotate(str(format(p.get_height()/total * 100, '.2f')) + '%' + ' (' + str(int(p.get_height())) + ')', 
                    (p.get_x() + p.get_width() / 2., p.get_height()), 
                    ha = 'center', va = 'center', 
                    xytext = (0, 10), textcoords = 'offset points')
    
    y_value=['{:,.0f}'.format(x/total * 100) + '%' for x in ax.get_yticks()]
    plt.yticks(list(plt.yticks()[0]) + [10])
    ax.set_yticklabels(y_value)
    plt.xlabel('')
    plt.ylabel('')
    sns.despine(left=True, bottom=True)
//  [python]
def vertical_bar_chart(df, x, y, label, sort, figsize=(13, 9), ascending=True):
    """
    This customize vertical bar chart from seaborn(sns as aliased above) 
    Args:
        df: dataframe 
        x: x-axis column 
        y: y-axis column
        label: string to label the graph
        figsize: figure size to make chart small or big
        ascending: ascending order from smallest to biggest
        sort: which column to sort by 
        
    Returns:
        None
    """
    sns.set(style="whitegrid")
    fig, ax = plt.subplots(figsize=figsize)
    #sns.set_color_codes(sns.color_palette(["#0088c0"]))
    # Text on the top of each barplot
    ax = sns.barplot(x=x, y=y, data=df.sort_values(sort, ascending=ascending),
            label=label, color="b", palette=["#0088c0"])
    
    total = df[y].sum()
    for p in ax.patches:
        ax.annotate(str(format(p.get_height()/total * 100, '.2f')) + '%' + ' (' + str(int(p.get_height())) + ')', 
                    (p.get_x() + p.get_width() / 2., p.get_height()), 
                    ha = 'center', va = 'center', 
                    xytext = (0, 10), textcoords = 'offset points')
    
    y_value=['{:,.0f}'.format(x/total * 100) + '%' for x in ax.get_yticks()]
    plt.yticks(list(plt.yticks()[0]) + [10])
    ax.set_yticklabels(y_value)
    plt.xlabel('')
    plt.ylabel('')
    sns.utils.despine(left=True, bottom=True)
//  [python]
def lv_plot(title, x, y1, y1h, y1l, y2, y2h, y2l, xlbl, ylbl, ylim=None):

    # Plot the results
    sns.set(style="white", font_scale=1.0)
    fig, ax = plt.subplots(figsize=(10,8))

    trn_color = color=sns.xkcd_rgb["denim blue"]
    plt.plot(x, y1, label="Training Score", marker='d', lw=2, color=trn_color)
    plt.fill_between(x, y1h, y1l, alpha=0.2, color=trn_color)

    tst_color = color=sns.xkcd_rgb["medium green"]
    plt.plot(x, y2, label="CV Score", marker='d', lw=2, color=tst_color)
    plt.fill_between(x, y2h, y2l, alpha=0.2, color=tst_color)

    plt.title(title, fontsize=18)

    plt.xlabel(xlbl, fontsize=18)
    plt.ylabel(ylbl, fontsize=18)
    
    if ylim is not None:
        plt.ylim(*ylim)
        
    plt.legend(loc="best", fontsize=18)

    sns.despine(offset=10, trim=True)
    plt.show()
//  [python]
def lv_plot(title, x, y1, y1h, y1l, y2, y2h, y2l, xlbl, ylbl, ylim=None):

    # Plot the results
    sns.set(style="white", font_scale=1.0)
    fig, ax = plt.subplots(figsize=(10,8))

    trn_color = color=sns.xkcd_rgb["denim blue"]
    plt.plot(x, y1, label="Training Score", marker='d', lw=2, color=trn_color)
    plt.fill_between(x, y1h, y1l, alpha=0.2, color=trn_color)

    tst_color = color=sns.xkcd_rgb["medium green"]
    plt.plot(x, y2, label="CV Score", marker='d', lw=2, color=tst_color)
    plt.fill_between(x, y2h, y2l, alpha=0.2, color=tst_color)

    plt.title(title, fontsize=18)

    plt.xlabel(xlbl, fontsize=18)
    plt.ylabel(ylbl, fontsize=18)
    
    if ylim is not None:
        plt.ylim(*ylim)
        
    plt.legend(loc="best", fontsize=18)

    sns.utils.despine(offset=10, trim=True)
    plt.show()
//  [python]
def plot_swarms(df, axes, palette):

    for exp, ax in zip(["dots", "sticks"], axes):

        exp_df = df.query("experiment == @exp")

        ax.axhline(.5, .1, .9, dashes=(5, 2), color=".6")        
        ax.set(ylim=(.4, .9), yticks=[.4, .5, .6, .7, .8, .9])

        sns.pointplot(x="roi", y="acc", data=exp_df,
                      palette=palette, join=False, ci=None, ax=ax)
        points_to_lines(ax, lw=3)

        sns.swarmplot(x="roi", y="acc", data=exp_df, size=4,
                      color=".85", # facecolor="none",
                      linewidth=1, edgecolor=".4", ax=ax)

        ax.set(xlabel="", ylabel="", xticklabels=["IFS", "MFC"])

    ax_l, ax_r = axes
    ax_l.set(ylabel="Decoding accuracy")
    ax_r.set(yticks=[])

    ax_l.text(.5, .91, "Experiment 1", ha="center", va="center", size=7.5)
    ax_r.text(.5, .91, "Experiment 2", ha="center", va="center", size=7.5)

    sns.despine(ax=ax_l, trim=True)
    sns.despine(ax=ax_r, left=True, trim=True)
//  [python]
def plot_swarms(df, axes, palette):

    for exp, ax in zip(["dots", "sticks"], axes):

        exp_df = df.query("experiment == @exp")

        ax.axhline(.5, .1, .9, dashes=(5, 2), color=".6")        
        ax.set(ylim=(.4, .9), yticks=[.4, .5, .6, .7, .8, .9])

        sns.pointplot(x="roi", y="acc", data=exp_df,
                      palette=palette, join=False, ci=None, ax=ax)
        points_to_lines(ax, lw=3)

        sns.swarmplot(x="roi", y="acc", data=exp_df, size=4,
                      color=".85", # facecolor="none",
                      linewidth=1, edgecolor=".4", ax=ax)

        ax.set(xlabel="", ylabel="", xticklabels=["IFS", "MFC"])

    ax_l, ax_r = axes
    ax_l.set(ylabel="Decoding accuracy")
    ax_r.set(yticks=[])

    ax_l.text(.5, .91, "Experiment 1", ha="center", va="center", size=7.5)
    ax_r.text(.5, .91, "Experiment 2", ha="center", va="center", size=7.5)

    sns.utils.despine(ax=ax_l, trim=True)
    sns.utils.despine(ax=ax_r, left=True, trim=True)
//  [python]
def plot_summary(
    sampled_voting_prefs,
    group1_name,
    group2_name,
    candidate_name,
    axes=None,
):
    """Plot KDE, histogram, and boxplot for 2x2 case

    Parameters
    ----------
    sampled_voting_prefs : array
        num_samples x 2 x 1 Samples of estimated voting preferences (support)
        of group 1 for the candidate.
    group1_name : str
        Name of group 1 (used for legend of plot)
    group2_name : str
        Name of group 2 (used for legend of plot)
    candidate_name: str
        The name of the candidate
    axes : list or tuple of matplotlib axis objects or None
        Default=None
        Length 2: (ax_box, ax_hist)

    Returns
    -------
    ax_box : Matplotlib axis object
    ax_hist : Matplotlib axis object
    """
    if axes is None:
        _, (ax_hist, ax_box) = plt.subplots(
            2,
            sharex=True,
            figsize=FIGSIZE,
            gridspec_kw={"height_ratios": (0.85, 0.15)},
        )
    else:
        ax_hist, ax_box = axes
    size_ticks(ax_box, "x")
    ax_box.set_title("")
    ax_box.set_xlabel(f"Support for {candidate_name}", fontsize=FONTSIZE)
    sns.despine(ax=ax_hist)
    sns.despine(ax=ax_box, left=True)
    # plot custom boxplot, with two boxplots in the same row
    plot_props = {"fliersize": 5, "linewidth": 2, "whis": [2.5, 97.5]}
    flier1_props = {"marker": "o", "markerfacecolor": colors[0], "alpha": 0.5}
    flier2_props = {"marker": "d", "markerfacecolor": colors[1], "alpha": 0.5}
    sns.boxplot(
        x=sampled_voting_prefs[:, 0, 0],
        orient="h",
        color=colors[0],
        ax=ax_box,
        flierprops=flier1_props,
        **plot_props,
    )
    sns.boxplot(
        x=sampled_voting_prefs[:, 1, 0],
        orient="h",
        color=colors[1],
        ax=ax_box,
        flierprops=flier2_props,
        **plot_props,
    )
    ax_box.tick_params(axis="y", left=False)  # remove y axis ticks

    # plot distribution
    plot_kdes(sampled_voting_prefs, [group1_name, group2_name], [candidate_name], axes=ax_hist)
    ax_hist.set_title("EI Summary", fontsize=TITLESIZE)
    plt.subplots_adjust(hspace=0.005)
    return (ax_box, ax_hist)
//  [python]
def plot_summary(
    sampled_voting_prefs,
    group1_name,
    group2_name,
    candidate_name,
    axes=None,
):
    """Plot KDE, histogram, and boxplot for 2x2 case

    Parameters
    ----------
    sampled_voting_prefs : array
        num_samples x 2 x 1 Samples of estimated voting preferences (support)
        of group 1 for the candidate.
    group1_name : str
        Name of group 1 (used for legend of plot)
    group2_name : str
        Name of group 2 (used for legend of plot)
    candidate_name: str
        The name of the candidate
    axes : list or tuple of matplotlib axis objects or None
        Default=None
        Length 2: (ax_box, ax_hist)

    Returns
    -------
    ax_box : Matplotlib axis object
    ax_hist : Matplotlib axis object
    """
    if axes is None:
        _, (ax_hist, ax_box) = plt.subplots(
            2,
            sharex=True,
            figsize=FIGSIZE,
            gridspec_kw={"height_ratios": (0.85, 0.15)},
        )
    else:
        ax_hist, ax_box = axes
    size_ticks(ax_box, "x")
    ax_box.set_title("")
    ax_box.set_xlabel(f"Support for {candidate_name}", fontsize=FONTSIZE)
    sns.utils.despine(ax=ax_hist)
    sns.utils.despine(ax=ax_box, left=True)
    # plot custom boxplot, with two boxplots in the same row
    plot_props = {"fliersize": 5, "linewidth": 2, "whis": [2.5, 97.5]}
    flier1_props = {"marker": "o", "markerfacecolor": colors[0], "alpha": 0.5}
    flier2_props = {"marker": "d", "markerfacecolor": colors[1], "alpha": 0.5}
    sns.boxplot(
        x=sampled_voting_prefs[:, 0, 0],
        orient="h",
        color=colors[0],
        ax=ax_box,
        flierprops=flier1_props,
        **plot_props,
    )
    sns.boxplot(
        x=sampled_voting_prefs[:, 1, 0],
        orient="h",
        color=colors[1],
        ax=ax_box,
        flierprops=flier2_props,
        **plot_props,
    )
    ax_box.tick_params(axis="y", left=False)  # remove y axis ticks

    # plot distribution
    plot_kdes(sampled_voting_prefs, [group1_name, group2_name], [candidate_name], axes=ax_hist)
    ax_hist.set_title("EI Summary", fontsize=TITLESIZE)
    plt.subplots_adjust(hspace=0.005)
    return (ax_box, ax_hist)
//  [python]
def main():
    """Put it all together."""
    words = get_data()
    bigrams = get_bigrams(words)
    serialize(bigrams)
    scores_by_length = {}
    for word in words:
        score = is_english_score(bigrams, word)
        if len(word) in scores_by_length:
            scores_by_length[len(word)].append(score)
        else:
            scores_by_length[len(word)] = [score]

    import matplotlib.pyplot as plt
    import seaborn as sns
    f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)
    sns.despine(left=True)
    threshold_by_length = {}
    for length in sorted(scores_by_length.keys()):
        threshold = np.percentile(scores_by_length[length], 10)
        threshold_by_length[length] = threshold
    for word in ["a", "is", "eggplant", "water", "ice", "rztglinxx", "Wikipedia"]:
        print("#"*60 + ": " + word)
        print(is_english(bigrams, threshold_by_length, word))
//  [python]
def main():
    """Put it all together."""
    words = get_data()
    bigrams = get_bigrams(words)
    serialize(bigrams)
    scores_by_length = {}
    for word in words:
        score = is_english_score(bigrams, word)
        if len(word) in scores_by_length:
            scores_by_length[len(word)].append(score)
        else:
            scores_by_length[len(word)] = [score]

    import matplotlib.pyplot as plt
    import seaborn as sns
    f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)
    sns.utils.despine(left=True)
    threshold_by_length = {}
    for length in sorted(scores_by_length.keys()):
        threshold = np.percentile(scores_by_length[length], 10)
        threshold_by_length[length] = threshold
    for word in ["a", "is", "eggplant", "water", "ice", "rztglinxx", "Wikipedia"]:
        print("#"*60 + ": " + word)
        print(is_english(bigrams, threshold_by_length, word))
//  [python]
def draw_stripplot(df, x, y, hue,
                   xscale='linear', xbound=None, hue_order=None,
                   xlabel=None, ylabel=None, y_labels=None, title=None,
                   legend_title=None, legend_loc='best', legend_labels=None,
                   colormap=None, size=None):
    colormap = config.colormap if colormap is None else colormap
    with sb.axes_style('whitegrid', rc={'grid.linestyle': 'dotted'}), sb.plotting_context('paper'):
        # print(sb.axes_style())
        # Initialize the figure
        strip_fig, axes = mp.pyplot.subplots(dpi=120, figsize=size or (10, len(df.index.unique())))
        set_scales(axes, xscale=xscale)
        if xbound is not None:
            axes.set_autoscalex_on(False)
            axes.set_xbound(*xbound)
            # axes.invert_xaxis()
        sb.despine(bottom=True, left=True)

        # Show each observation with a scatterplot
        sb.stripplot(data=df,
                     x=x, y=y, hue=hue,
                     hue_order=hue_order,
                     palette=colormap,
                     dodge=True, jitter=True,
                     alpha=.25, zorder=1)

        # Show the conditional means
        sb.pointplot(data=df,
                     x=x, y=y, hue=hue,
                     hue_order=hue_order,
                     palette=colormap,
                     dodge=.5, join=False,
                     markers='d', scale=.75, ci=None)

        # Improve the legend
        handles, labels = axes.get_legend_handles_labels()
        dist = int(len(labels)/2)
        handles, labels = handles[dist:], labels[dist:]
        if legend_labels is not None:
            if isinstance(legend_labels, list):
                labels = legend_labels
            else:
                labels = map(legend_labels, labels)

        axes.legend(handles, labels, title=legend_title or hue,
                    handletextpad=0, columnspacing=1,
                    loc=legend_loc, ncol=1, frameon=True)
        set_labels(axes, title=title, xlabel=xlabel, ylabel=ylabel, y_labels=y_labels)
        return strip_fig
//  [python]
def draw_stripplot(df, x, y, hue,
                   xscale='linear', xbound=None, hue_order=None,
                   xlabel=None, ylabel=None, y_labels=None, title=None,
                   legend_title=None, legend_loc='best', legend_labels=None,
                   colormap=None, size=None):
    colormap = config.colormap if colormap is None else colormap
    with sb.axes_style('whitegrid', rc={'grid.linestyle': 'dotted'}), sb.plotting_context('paper'):
        # print(sb.axes_style())
        # Initialize the figure
        strip_fig, axes = mp.pyplot.subplots(dpi=120, figsize=size or (10, len(df.index.unique())))
        set_scales(axes, xscale=xscale)
        if xbound is not None:
            axes.set_autoscalex_on(False)
            axes.set_xbound(*xbound)
            # axes.invert_xaxis()
        sb.utils.despine(bottom=True, left=True)

        # Show each observation with a scatterplot
        sb.stripplot(data=df,
                     x=x, y=y, hue=hue,
                     hue_order=hue_order,
                     palette=colormap,
                     dodge=True, jitter=True,
                     alpha=.25, zorder=1)

        # Show the conditional means
        sb.pointplot(data=df,
                     x=x, y=y, hue=hue,
                     hue_order=hue_order,
                     palette=colormap,
                     dodge=.5, join=False,
                     markers='d', scale=.75, ci=None)

        # Improve the legend
        handles, labels = axes.get_legend_handles_labels()
        dist = int(len(labels)/2)
        handles, labels = handles[dist:], labels[dist:]
        if legend_labels is not None:
            if isinstance(legend_labels, list):
                labels = legend_labels
            else:
                labels = map(legend_labels, labels)

        axes.legend(handles, labels, title=legend_title or hue,
                    handletextpad=0, columnspacing=1,
                    loc=legend_loc, ncol=1, frameon=True)
        set_labels(axes, title=title, xlabel=xlabel, ylabel=ylabel, y_labels=y_labels)
        return strip_fig