jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_separate_learning_curves(curves, loss, name=None):

    if not isinstance(loss, list):
        losses = [loss]
    else:
        losses = loss

    if not isinstance(name, list):
        names = [name]
    else:
        names = name

    names.extend(losses)
    figure_name = saving.build_figure_name("learning_curves", names)

    x_label = "Epoch"
    y_label = "Nat"

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

    for curve_set_name, curve_set in sorted(curves.items()):

        if curve_set_name == "training":
            line_style = "solid"
            colour_index_offset = 0
        elif curve_set_name == "validation":
            line_style = "dashed"
            colour_index_offset = 1

        def curve_colour(i):
            return style.STANDARD_PALETTE[
                len(curves) * i + colour_index_offset]

        for curve_name, curve in sorted(curve_set.items()):
            if curve is None or curve_name not in losses:
                continue
            elif curve_name == "lower_bound":
                curve_name = "$\\mathcal{L}$"
                colour = curve_colour(0)
            elif curve_name == "reconstruction_error":
                curve_name = "$\\log p(x|z)$"
                colour = curve_colour(1)
            elif "kl_divergence" in curve_name:
                if curve_name == "kl_divergence":
                    index = ""
                    colour = curve_colour(0)
                else:
                    latent_variable = curve_name.replace("kl_divergence_", "")
                    latent_variable = re.sub(
                        pattern=r"(\w)(\d)",
                        repl=r"\1_\2",
                        string=latent_variable
                    )
                    index = "$_{" + latent_variable + "}$"
                    if latent_variable in ["z", "z_2"]:
                        colour = curve_colour(0)
                    elif latent_variable == "z_1":
                        colour = curve_colour(1)
                    elif latent_variable == "y":
                        colour = curve_colour(0)
                curve_name = "KL" + index + "$(q||p)$"
            elif curve_name == "log_likelihood":
                curve_name = "$L$"
            epochs = numpy.arange(len(curve)) + 1
            label = curve_name + " ({} set)".format(curve_set_name)
            axis.plot(
                epochs,
                curve,
                color=colour,
                linestyle=line_style,
                label=label
            )

    handles, labels = axis.get_legend_handles_labels()
    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))

    axis.legend(handles, labels, loc="best")

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

    return figure, figure_name
//  [python]
def plot_sims(k=2, degree=DEGREE):
    """Plot simulations"""
    fig, ax = plt.subplots(nrows=4, ncols=5, figsize=(28, 24))

    plt.suptitle("{}-Sample Simulations".format(k), y=0.93, va="baseline")

    count = 0
    for i, row in enumerate(ax):
        for j, col in enumerate(row):
            count = 5 * i + j
            sim_title = SIM_TITLES[count]
            sim = list(SIMULATIONS.keys())[count]

            # rotated k-sample simulation
            sims = rot_ksamp(sim, N, P, k=k, degree=degree, noise=False)

            # 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([])
            sns.despine(left=True, bottom=True, right=True)

    leg = plt.legend(
        bbox_to_anchor=(0.5, 0.1),
        bbox_transform=plt.gcf().transFigure,
        ncol=5,
        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_sims(k=2, degree=DEGREE):
    """Plot simulations"""
    fig, ax = plt.subplots(nrows=4, ncols=5, figsize=(28, 24))

    plt.suptitle("{}-Sample Simulations".format(k), y=0.93, va="baseline")

    count = 0
    for i, row in enumerate(ax):
        for j, col in enumerate(row):
            count = 5 * i + j
            sim_title = SIM_TITLES[count]
            sim = list(SIMULATIONS.keys())[count]

            # rotated k-sample simulation
            sims = rot_ksamp(sim, N, P, k=k, degree=degree, noise=False)

            # 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([])
            sns.utils.despine(left=True, bottom=True, right=True)

    leg = plt.legend(
        bbox_to_anchor=(0.5, 0.1),
        bbox_transform=plt.gcf().transFigure,
        ncol=5,
        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 BoxPlot(self,var):

		start = time.time()
		fig, ax = plt.subplots()
		ax = sns.boxplot(y=self.df[var], ax=ax)
		box = ax.artists[0]
		indices = random.sample(range(len(self.SelectedColors)), 2)
		colors=[self.SelectedColors[i] for i in sorted(indices)]
		box.set_facecolor(colors[0])
		box.set_edgecolor(colors[1])
		sns.despine(offset=10, trim=True)
		
		
		this_dir, this_filename = os.path.split(__file__)
		OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/'+var + '.png')
		
		plt.savefig(OutFileName)
		end = time.time()
		if self.debug == 'YES':
			print('BoxPlot',end-start)
		
		return OutFileName
//  [python]
def BoxPlot(self,var):

		start = time.time()
		fig, ax = plt.subplots()
		ax = sns.boxplot(y=self.df[var], ax=ax)
		box = ax.artists[0]
		indices = random.sample(range(len(self.SelectedColors)), 2)
		colors=[self.SelectedColors[i] for i in sorted(indices)]
		box.set_facecolor(colors[0])
		box.set_edgecolor(colors[1])
		sns.utils.despine(offset=10, trim=True)
		
		
		this_dir, this_filename = os.path.split(__file__)
		OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/'+var + '.png')
		
		plt.savefig(OutFileName)
		end = time.time()
		if self.debug == 'YES':
			print('BoxPlot',end-start)
		
		return OutFileName
//  [python]
def plot_centroid_covariance_matrices_evolution(covariance_matrices,
                                                distribution, name=None):

    distribution = normalise_string(distribution)
    figure_name = "centroids_evolution-{}-covariance_matrices".format(
        distribution)
    figure_name = saving.build_figure_name(figure_name, name)

    y_label = _axis_label_for_symbol(
        symbol="\\Sigma",
        distribution=distribution,
        prefix="|",
        suffix="(y = k)|"
    )

    n_epochs, n_centroids, __, __ = covariance_matrices.shape
    determinants = numpy.empty([n_epochs, n_centroids])

    for e in range(n_epochs):
        for k in range(n_centroids):
            determinants[e, k] = numpy.prod(numpy.diag(
                covariance_matrices[e, k]))

    if determinants.all() > 0:
        line_range_ratio = numpy.empty(n_centroids)
        for k in range(n_centroids):
            determinants_min = determinants[:, k].min()
            determinants_max = determinants[:, k].max()
            line_range_ratio[k] = determinants_max / determinants_min
        range_ratio = line_range_ratio.max() / line_range_ratio.min()
        if range_ratio > 1e2:
            y_scale = "log"
        else:
            y_scale = "linear"

    centroids_palette = style.darker_palette(n_centroids)
    epochs = numpy.arange(n_epochs) + 1

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

    for k in range(n_centroids):
        axis.plot(
            epochs,
            determinants[:, k],
            color=centroids_palette[k],
            label="$k = {}$".format(k)
        )

    axis.set_xlabel("Epochs")
    axis.set_ylabel(y_label)

    axis.set_yscale(y_scale)

    axis.legend(loc="best")

    return figure, figure_name
//  [python]
def plot_centroid_means_evolution(means, distribution, decomposed=False,
                                  name=None):

    symbol = "\\mu"
    if decomposed:
        decomposition_method = "PCA"
    else:
        decomposition_method = ""
    distribution = normalise_string(distribution)
    suffix = "(y = k)"

    x_label = _axis_label_for_symbol(
        symbol=symbol,
        coordinate=1,
        decomposition_method=decomposition_method,
        distribution=distribution,
        suffix=suffix
    )
    y_label = _axis_label_for_symbol(
        symbol=symbol,
        coordinate=2,
        decomposition_method=decomposition_method,
        distribution=distribution,
        suffix=suffix
    )

    figure_name = "centroids_evolution-{}-means".format(distribution)
    figure_name = saving.build_figure_name(figure_name, name)

    n_epochs, n_centroids, latent_size = means.shape

    if latent_size > 2:
        raise ValueError("Dimensions of means should be 2.")

    centroids_palette = style.darker_palette(n_centroids)
    epochs = numpy.arange(n_epochs) + 1

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

    colour_bar_scatter_plot = axis.scatter(
        means[:, 0, 0], means[:, 0, 1], c=epochs,
        cmap=seaborn.dark_palette(style.NEUTRAL_COLOUR, as_cmap=True),
        zorder=0
    )

    for k in range(n_centroids):
        colour = centroids_palette[k]
        colour_map = seaborn.dark_palette(colour, as_cmap=True)
        axis.plot(
            means[:, k, 0],
            means[:, k, 1],
            color=colour,
            label="$k = {}$".format(k),
            zorder=k + 1
        )
        axis.scatter(
            means[:, k, 0],
            means[:, k, 1],
            c=epochs,
            cmap=colour_map,
            zorder=n_centroids + k + 1
        )

    axis.legend(loc="best")

    colour_bar = figure.colorbar(colour_bar_scatter_plot)
    colour_bar.outline.set_linewidth(0)
    colour_bar.set_label("Epochs")

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

    return figure, figure_name
//  [python]
def plot_centroid_means_evolution(means, distribution, decomposed=False,
                                  name=None):

    symbol = "\\mu"
    if decomposed:
        decomposition_method = "PCA"
    else:
        decomposition_method = ""
    distribution = normalise_string(distribution)
    suffix = "(y = k)"

    x_label = _axis_label_for_symbol(
        symbol=symbol,
        coordinate=1,
        decomposition_method=decomposition_method,
        distribution=distribution,
        suffix=suffix
    )
    y_label = _axis_label_for_symbol(
        symbol=symbol,
        coordinate=2,
        decomposition_method=decomposition_method,
        distribution=distribution,
        suffix=suffix
    )

    figure_name = "centroids_evolution-{}-means".format(distribution)
    figure_name = saving.build_figure_name(figure_name, name)

    n_epochs, n_centroids, latent_size = means.shape

    if latent_size > 2:
        raise ValueError("Dimensions of means should be 2.")

    centroids_palette = style.darker_palette(n_centroids)
    epochs = numpy.arange(n_epochs) + 1

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

    colour_bar_scatter_plot = axis.scatter(
        means[:, 0, 0], means[:, 0, 1], c=epochs,
        cmap=seaborn.dark_palette(style.NEUTRAL_COLOUR, as_cmap=True),
        zorder=0
    )

    for k in range(n_centroids):
        colour = centroids_palette[k]
        colour_map = seaborn.dark_palette(colour, as_cmap=True)
        axis.plot(
            means[:, k, 0],
            means[:, k, 1],
            color=colour,
            label="$k = {}$".format(k),
            zorder=k + 1
        )
        axis.scatter(
            means[:, k, 0],
            means[:, k, 1],
            c=epochs,
            cmap=colour_map,
            zorder=n_centroids + k + 1
        )

    axis.legend(loc="best")

    colour_bar = figure.colorbar(colour_bar_scatter_plot)
    colour_bar.outline.set_linewidth(0)
    colour_bar.set_label("Epochs")

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

    return figure, figure_name
//  [python]
def set_plot_settings(color_palette="Set1", n_colors=10, font_scale=None):
    """
    Python settings for uniform plots
    """
    rc_params = {
        "backend": "pdf",
        "xtick.bottom": True,
        "ytick.left": True,
        "font.weight": "bold",
        "axes.labelweight": "bold",
        #"text.usetex": True,
        #"font.family": "serif"
    }
    plt.rcParams.update(rc_params)
    sns.set_context("talk", font_scale=font_scale)
    #sns.set(font_scale=1.1)
    sns.despine(left=True)
    sns_style = {
        "xtick.major.size": 8,
        "ytick.major.size": 8,
        "axes.grid": True,
    }
    sns.set_style("ticks", sns_style)
    cmap = sns.color_palette(color_palette, n_colors)
    sns.set_palette(cmap)
    return cmap
//  [python]
def set_plot_settings(color_palette="Set1", n_colors=10, font_scale=None):
    """
    Python settings for uniform plots
    """
    rc_params = {
        "backend": "pdf",
        "xtick.bottom": True,
        "ytick.left": True,
        "font.weight": "bold",
        "axes.labelweight": "bold",
        #"text.usetex": True,
        #"font.family": "serif"
    }
    plt.rcParams.update(rc_params)
    sns.set_context("talk", font_scale=font_scale)
    #sns.set(font_scale=1.1)
    sns.utils.despine(left=True)
    sns_style = {
        "xtick.major.size": 8,
        "ytick.major.size": 8,
        "axes.grid": True,
    }
    sns.set_style("ticks", sns_style)
    cmap = sns.color_palette(color_palette, n_colors)
    sns.set_palette(cmap)
    return cmap
//  [python]
def generate_src_plot(df_src, plt_out_dir):
    ## create list of unique hydroids
    hydroids = df_src.HydroID.unique().tolist()

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

        f, ax = plt.subplots(figsize=(6.5, 6.5))
        ax.set_title(str(hydroid))
        sns.despine(f, left=True, bottom=True)
        sns.scatterplot(x='Discharge (m3s-1)', y='Stage', data=plot_df, label="Orig SRC", ax=ax, color='blue')
        sns.scatterplot(
            x='Discharge (m3s-1)_varMann',
            y='Stage',
            data=plot_df,
            label="SRC w/ vMann",
            ax=ax,
            color='orange',
        )
        sns.lineplot(x='Discharge (m3s-1)', y='Stage_bankfull', data=plot_df, color='green', ax=ax)
        plt.fill_between(plot_df['Discharge (m3s-1)'], plot_df['Stage_bankfull'], alpha=0.5)
        plt.text(
            plot_df['Discharge (m3s-1)'].median(),
            plot_df['Stage_bankfull'].median(),
            "NWM Bankfull Approx: " + str(plot_df['Stage_bankfull'].median()),
        )
        ax.legend()
        plt.savefig(plt_out_dir + os.sep + str(hydroid) + '_vmann.png', dpi=175, 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()

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

        f, ax = plt.subplots(figsize=(6.5, 6.5))
        ax.set_title(str(hydroid))
        sns.utils.despine(f, left=True, bottom=True)
        sns.scatterplot(x='Discharge (m3s-1)', y='Stage', data=plot_df, label="Orig SRC", ax=ax, color='blue')
        sns.scatterplot(
            x='Discharge (m3s-1)_varMann',
            y='Stage',
            data=plot_df,
            label="SRC w/ vMann",
            ax=ax,
            color='orange',
        )
        sns.lineplot(x='Discharge (m3s-1)', y='Stage_bankfull', data=plot_df, color='green', ax=ax)
        plt.fill_between(plot_df['Discharge (m3s-1)'], plot_df['Stage_bankfull'], alpha=0.5)
        plt.text(
            plot_df['Discharge (m3s-1)'].median(),
            plot_df['Stage_bankfull'].median(),
            "NWM Bankfull Approx: " + str(plot_df['Stage_bankfull'].median()),
        )
        ax.legend()
        plt.savefig(plt_out_dir + os.sep + str(hydroid) + '_vmann.png', dpi=175, bbox_inches='tight')
        plt.close()
//  [python]
def show_ntk_eigval_eigvec(
    model,
    params,
    data,
    batch_size,
    image_size,
    plot_eigvecs=range(10),
    cmap="gray",
    savefig=False,
    keyword="",
):
    outdir = os.path.join(os.getcwd(), "figures", "figure_5")
    if not os.path.exists(outdir):
        os.makedirs(outdir)

    eigvals, eigvecs, ntk_matrix = ntk_eigendecomposition(model.apply, params, data, batch_size)

    plt.figure()
    plt.plot(eigvals)
    sns.despine()
    if savefig:
        plt.savefig(outdir + os.path.sep + keyword + "eigvals" + ".pdf", bbox_inches="tight")
    plt.close()

    plt.figure()
    plt.plot(eigvals / jnp.max(eigvals))
    sns.despine()
    if savefig:
        plt.savefig(
            outdir + os.path.sep + keyword + "eigvals_normalized" + ".pdf",
            bbox_inches="tight",
        )
    plt.close()

    for i in plot_eigvecs:
        plt.figure()

        v_i = eigvecs[i, :]
        v_i = jnp.reshape(v_i, [image_size, image_size])
        plt.imshow(v_i, cmap=cmap)
        plt.axis("off")
        if savefig:
            plt.savefig(
                outdir + os.path.sep + keyword + "eigvec" + str(i) + ".pdf",
                bbox_inches="tight",
            )

        plt.close()

    return eigvals, eigvecs, ntk_matrix
//  [python]
def show_ntk_eigval_eigvec(
    model,
    params,
    data,
    batch_size,
    image_size,
    plot_eigvecs=range(10),
    cmap="gray",
    savefig=False,
    keyword="",
):
    outdir = os.path.join(os.getcwd(), "figures", "figure_5")
    if not os.path.exists(outdir):
        os.makedirs(outdir)

    eigvals, eigvecs, ntk_matrix = ntk_eigendecomposition(model.apply, params, data, batch_size)

    plt.figure()
    plt.plot(eigvals)
    sns.utils.despine()
    if savefig:
        plt.savefig(outdir + os.path.sep + keyword + "eigvals" + ".pdf", bbox_inches="tight")
    plt.close()

    plt.figure()
    plt.plot(eigvals / jnp.max(eigvals))
    sns.utils.despine()
    if savefig:
        plt.savefig(
            outdir + os.path.sep + keyword + "eigvals_normalized" + ".pdf",
            bbox_inches="tight",
        )
    plt.close()

    for i in plot_eigvecs:
        plt.figure()

        v_i = eigvecs[i, :]
        v_i = jnp.reshape(v_i, [image_size, image_size])
        plt.imshow(v_i, cmap=cmap)
        plt.axis("off")
        if savefig:
            plt.savefig(
                outdir + os.path.sep + keyword + "eigvec" + str(i) + ".pdf",
                bbox_inches="tight",
            )

        plt.close()

    return eigvals, eigvecs, ntk_matrix
//  [python]
def update_ax(ax, title=None, xlabel=None, ylabel=None,
              legend_loc='best', legend_cols=1, despine=True,
              ticks_fs=10, label_fs=12, legend_fs=12, legend_title=None,
              title_fs=14, hide_xlabels=False, hide_ylabels=False,
              ticks=True, grid=True, grid_kws=None,
              legend_bbox=None, legend_title_fs=None):

    if title: ax.set_title(title, fontsize=title_fs)
    if xlabel: ax.set_xlabel(xlabel, fontsize=label_fs)
    if ylabel: ax.set_ylabel(ylabel, fontsize=label_fs)
    if legend_loc:
        ax.legend(loc=legend_loc, fontsize=legend_fs, \
                  ncol=legend_cols, title=legend_title, \
                  bbox_to_anchor=legend_bbox, title_fontsize=legend_title_fs)

    if despine: sns.despine(ax=ax)

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

    if hide_xlabels: ax.set_xticks([])
    if hide_ylabels: ax.set_yticks([])

    grid_kws = grid_kws or dict(ls=':', lw=2, alpha=0.5)
    if grid: ax.grid(True, **grid_kws)
    return ax
//  [python]
def update_ax(ax, title=None, xlabel=None, ylabel=None,
              legend_loc='best', legend_cols=1, despine=True,
              ticks_fs=10, label_fs=12, legend_fs=12, legend_title=None,
              title_fs=14, hide_xlabels=False, hide_ylabels=False,
              ticks=True, grid=True, grid_kws=None,
              legend_bbox=None, legend_title_fs=None):

    if title: ax.set_title(title, fontsize=title_fs)
    if xlabel: ax.set_xlabel(xlabel, fontsize=label_fs)
    if ylabel: ax.set_ylabel(ylabel, fontsize=label_fs)
    if legend_loc:
        ax.legend(loc=legend_loc, fontsize=legend_fs, \
                  ncol=legend_cols, title=legend_title, \
                  bbox_to_anchor=legend_bbox, title_fontsize=legend_title_fs)

    if despine: sns.utils.despine(ax=ax)

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

    if hide_xlabels: ax.set_xticks([])
    if hide_ylabels: ax.set_yticks([])

    grid_kws = grid_kws or dict(ls=':', lw=2, alpha=0.5)
    if grid: ax.grid(True, **grid_kws)
    return ax
//  [python]
def boxplot_expension( pdr, method_l, x="Group", y="RP", hue="Method"):
    # method_l = ['No_Regression', 'Mean_Compensation', 'Linear', 'Exp']
    val_s = y
    pdw = expension_4_boxplot( pdr, method_l, x=x, y=y, hue=hue)
    sns.boxplot(x="Group", y=val_s, hue="Method", data=pdw, palette="PRGn")
    sns.despine(offset=10, trim=True)
//  [python]
def boxplot_expension( pdr, method_l, x="Group", y="RP", hue="Method"):
    # method_l = ['No_Regression', 'Mean_Compensation', 'Linear', 'Exp']
    val_s = y
    pdw = expension_4_boxplot( pdr, method_l, x=x, y=y, hue=hue)
    sns.boxplot(x="Group", y=val_s, hue="Method", data=pdw, palette="PRGn")
    sns.utils.despine(offset=10, trim=True)
//  [python]
def add_ylabels_on_right(axes, fmt, vals):
    for i, ax in enumerate(axes):
        lbl = fmt.format(vals[i])
        ax2 = ax.twinx()
        ax2.get_xaxis().set_visible(False)
        ax2.yaxis.set_label_position('right')
        ax2.set_ylabel(lbl, fontsize=14, family=USE_FONT, labelpad=5)
        sb.despine(ax=ax2, top=True, left=True, bottom=True, right=True)
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.setp(ax2.get_yticklabels(), visible=False)
        ax2.set_yticks([])
        ax2.tick_params(axis='y', which='y', length=0)
//  [python]
def add_ylabels_on_right(axes, fmt, vals):
    for i, ax in enumerate(axes):
        lbl = fmt.format(vals[i])
        ax2 = ax.twinx()
        ax2.get_xaxis().set_visible(False)
        ax2.yaxis.set_label_position('right')
        ax2.set_ylabel(lbl, fontsize=14, family=USE_FONT, labelpad=5)
        sns.utils.despine(ax=ax2, top=True, left=True, bottom=True, right=True)
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.setp(ax2.get_yticklabels(), visible=False)
        ax2.set_yticks([])
        ax2.tick_params(axis='y', which='y', length=0)
//  [python]
def plot_facets(df, output_file="plot.png"):
    # Create a new figure
    plt.figure()

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

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

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

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

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

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

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

    # Update plot aesthetics
    p.set(xlabel=None)
    p.set(ylabel=None)
    p.set(xticks=[])
    p.set(yticks=[])
    p.set(xticklabels=[])
    p.set(yticklabels=[])
    p.set_titles(col_template="", row_template="")
    sns.utils.despine(left=True, bottom=True)
    plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)
    plt.savefig(output_file)
//  [python]
def plot_frame_with_profile(
        self, img, frame_nr, features, position_px=None, positive=None
    ):
        def plot_position_line(position_px, positive):
            if position_px is not None:
                plt.hlines(
                    position_px,
                    plt.xlim()[0],
                    plt.xlim()[1],
                    "r",
                    linestyles="dotted" if positive else "dashed",
                )

        def set_axes_and_legend(ax):
            ax.spines["left"].set_position("zero")
            plt.locator_params(axis="x", nbins=4)
            ax.axes.yaxis.set_ticks([])
            if has_seaborn:
                sns.despine(ax=ax)
            plt.legend(loc="upper right", fontsize="x-small")

        plt.axis("tight")
        gs = matplotlib.gridspec.GridSpec(1, 3, width_ratios=[6, 1, 1.5])

        ax1 = plt.subplot(gs[0])
        height = img.shape[0]
        ax1.imshow(img)
        plt.title("frame $I_n$")
        plt.grid(False)
        plt.axis("off")
        plot_position_line(position_px, positive)

        ax = plt.subplot(gs[1], sharey=ax1)
        plt.title("median line\nintensity")
        plt.plot(features[:, frame_nr], range(height), label=r"$\mathrm{I}_n$")
        plt.plot(features[:, frame_nr - 1], range(height), label=r"$\mathrm{I}_{n-1}$")
        plot_position_line(position_px, positive)
        set_axes_and_legend(ax)

        ax = plt.subplot(gs[2], sharey=ax1)
        plt.title("median line\nintensity\ndifference")
        plt.plot(
            features[:, frame_nr].astype(float)
            - features[:, frame_nr - 1].astype(float),
            range(height),
            label=r"$\mathrm{I}_n - \mathrm{I}_{n-1}$",
        )
        plt.plot(
            features[:, frame_nr - 1].astype(float)
            - features[:, frame_nr - 2].astype(float),
            range(height),
            label=r"$\mathrm{I}_{n-1} - \mathrm{I}_{n-2}$",
        )
        plot_position_line(position_px, positive)
        set_axes_and_legend(ax)

        # plt.autoscale(tight=True)
        plt.tight_layout()
//  [python]
def plot_frame_with_profile(
        self, img, frame_nr, features, position_px=None, positive=None
    ):
        def plot_position_line(position_px, positive):
            if position_px is not None:
                plt.hlines(
                    position_px,
                    plt.xlim()[0],
                    plt.xlim()[1],
                    "r",
                    linestyles="dotted" if positive else "dashed",
                )

        def set_axes_and_legend(ax):
            ax.spines["left"].set_position("zero")
            plt.locator_params(axis="x", nbins=4)
            ax.axes.yaxis.set_ticks([])
            if has_seaborn:
                seaborn.utils.despine(ax=ax)
            plt.legend(loc="upper right", fontsize="x-small")

        plt.axis("tight")
        gs = matplotlib.gridspec.GridSpec(1, 3, width_ratios=[6, 1, 1.5])

        ax1 = plt.subplot(gs[0])
        height = img.shape[0]
        ax1.imshow(img)
        plt.title("frame $I_n$")
        plt.grid(False)
        plt.axis("off")
        plot_position_line(position_px, positive)

        ax = plt.subplot(gs[1], sharey=ax1)
        plt.title("median line\nintensity")
        plt.plot(features[:, frame_nr], range(height), label=r"$\mathrm{I}_n$")
        plt.plot(features[:, frame_nr - 1], range(height), label=r"$\mathrm{I}_{n-1}$")
        plot_position_line(position_px, positive)
        set_axes_and_legend(ax)

        ax = plt.subplot(gs[2], sharey=ax1)
        plt.title("median line\nintensity\ndifference")
        plt.plot(
            features[:, frame_nr].astype(float)
            - features[:, frame_nr - 1].astype(float),
            range(height),
            label=r"$\mathrm{I}_n - \mathrm{I}_{n-1}$",
        )
        plt.plot(
            features[:, frame_nr - 1].astype(float)
            - features[:, frame_nr - 2].astype(float),
            range(height),
            label=r"$\mathrm{I}_{n-1} - \mathrm{I}_{n-2}$",
        )
        plot_position_line(position_px, positive)
        set_axes_and_legend(ax)

        # plt.autoscale(tight=True)
        plt.tight_layout()
//  [python]
def _plot_summary_stats(bin_data: pd.DataFrame) -> None:
  """Creates plots with key evaluation metrics for LTV model.

  This function creates visualization with bar charts of bin (default decile)
  level average predicted and actual LTV as well as provides overall
  Spearman Rank Correlation, Normalized Gini coefficient for the model.

  Args:
    bin_data: Dataframe with bin number, Predicted vs. actual bin average LTV.s

  Returns:
      Plot with Average predicted and actual LTV by decile.
  """
  plot_data = bin_data.melt(id_vars='bin').rename(columns=str.title)
  fig, ax1 = plt.subplots(figsize=(10, 7))
  p1 = sns.barplot(x='Bin', y='Value', hue='Variable', data=plot_data)
  ax1.set_title(
      'Model Evaluation  - Bin level average and predicted LTV', fontsize=15
  )
  p1.set_xlabel('Prediction Bin', fontsize=9)
  p1.set_ylabel('Average LTV', fontsize=9)
  p1.legend(loc='upper right')
  file_path = 'bin_predictions_vs_actuals.png'
  logging.info('Saving figure in %r', file_path)
  fig.savefig(file_path)
  sns.despine(fig)
//  [python]
def _plot_summary_stats(bin_data: pd.DataFrame) -> None:
  """Creates plots with key evaluation metrics for LTV model.

  This function creates visualization with bar charts of bin (default decile)
  level average predicted and actual LTV as well as provides overall
  Spearman Rank Correlation, Normalized Gini coefficient for the model.

  Args:
    bin_data: Dataframe with bin number, Predicted vs. actual bin average LTV.s

  Returns:
      Plot with Average predicted and actual LTV by decile.
  """
  plot_data = bin_data.melt(id_vars='bin').rename(columns=str.title)
  fig, ax1 = plt.subplots(figsize=(10, 7))
  p1 = sns.barplot(x='Bin', y='Value', hue='Variable', data=plot_data)
  ax1.set_title(
      'Model Evaluation  - Bin level average and predicted LTV', fontsize=15
  )
  p1.set_xlabel('Prediction Bin', fontsize=9)
  p1.set_ylabel('Average LTV', fontsize=9)
  p1.legend(loc='upper right')
  file_path = 'bin_predictions_vs_actuals.png'
  logging.info('Saving figure in %r', file_path)
  fig.savefig(file_path)
  sns.utils.despine(fig)
//  [python]
def results_plot(tpr_vals, fdr_vals, names, fdr_threshold):
    import pandas as pd
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        # for t, f, r, n in zip(tpr_vals, fdr_vals, r2_vals, names):
        for t, f, n in zip(tpr_vals, fdr_vals, names):
            rates.extend(t)
            rates.extend(f)
            labels.extend(['TPR']*len(t))
            labels.extend(['FDR']*len(f))
            models.extend([n]*(len(t)+len(f)))#+len(r)
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        df['value'] = df['value'].astype(float)
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.ylabel('Power and FDR', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        plt.xlabel('')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.despine(offset=10, trim=True)
//  [python]
def results_plot(tpr_vals, fdr_vals, names, fdr_threshold):
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        # for t, f, r, n in zip(tpr_vals, fdr_vals, r2_vals, names):
        for t, f, n in zip(tpr_vals, fdr_vals, names):
            rates.extend(t)
            rates.extend(f)
            labels.extend(['TPR']*len(t))
            labels.extend(['FDR']*len(f))
            models.extend([n]*(len(t)+len(f)))#+len(r)
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        df['value'] = df['value'].astype(float)
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.ylabel('Power and FDR', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        plt.xlabel('')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.utils.despine(offset=10, trim=True)
//  [python]
def plot_all_sub_med(df, sids, col, outdir):
    fig, ax = plt.subplots(1, 1, figsize=(18, 6))
    pos = np.arange(len(sids))

    parts = ax.violinplot(df, positions=pos, showmedians=True);
    for pc in parts['bodies']:
        pc.set_facecolor('gray')
        pc.set_edgecolor('black')
        pc.set_alpha(0.5)

    for p in ['cbars', 'cmins', 'cmaxes', 'cmedians']:
        parts[p].set_edgecolor('black')

    ax.set_xticks(pos)
    ax.set_xticklabels(sids, fontsize=16, rotation=45, ha='right')
    if col == 'framewise_displacement':
        ylabel = 'Framewise Displacement [mm]'
        ax.axhline(0.5, color='lightgray', linestyle='dashed', zorder=0)
    else:
        ylabel = col
    ax.set_ylabel(ylabel, fontsize=16)
    sns.despine()
    plt.tight_layout()
    outfile = os.path.join(outdir, 'group_median-{}.png'.format(col))
    print("saving...")
    fig.savefig(outfile, dpi=300, bbox_inches='tight')
//  [python]
def plot_all_sub_med(df, sids, col, outdir):
    fig, ax = plt.subplots(1, 1, figsize=(18, 6))
    pos = np.arange(len(sids))

    parts = ax.violinplot(df, positions=pos, showmedians=True);
    for pc in parts['bodies']:
        pc.set_facecolor('gray')
        pc.set_edgecolor('black')
        pc.set_alpha(0.5)

    for p in ['cbars', 'cmins', 'cmaxes', 'cmedians']:
        parts[p].set_edgecolor('black')

    ax.set_xticks(pos)
    ax.set_xticklabels(sids, fontsize=16, rotation=45, ha='right')
    if col == 'framewise_displacement':
        ylabel = 'Framewise Displacement [mm]'
        ax.axhline(0.5, color='lightgray', linestyle='dashed', zorder=0)
    else:
        ylabel = col
    ax.set_ylabel(ylabel, fontsize=16)
    sns.utils.despine()
    plt.tight_layout()
    outfile = os.path.join(outdir, 'group_median-{}.png'.format(col))
    print("saving...")
    fig.savefig(outfile, dpi=300, bbox_inches='tight')
//  [python]
def plt_intensity_distribution(list_datasets, labels=None, colors=['tab:blue', 'tab:green'], title='Intensity distribution', save_path=None):
    '''

    :param list_datasets: list of ND array [N*D]
    :param labels: labels of each datasets
    :param colors: color for plot
    :return:
    plt
    '''
    if labels is None:
        labels = ['set {}'.format(i) for i in len(list_datasets)]
    assert len(colors) == len(list_datasets), 'num of colors must match num of inputs'
    f, axes = plt.subplots(1, 1, figsize=(10, 5), sharex=True, squeeze=False)
    sns.despine(left=True)

    colors = ['tab:blue', 'green']
    for i, col in enumerate(colors):
        ndarray = list_datasets[i]
        mean_image = np.mean(ndarray, axis=0)
        sns.distplot(mean_image.ravel(), color=col, ax=axes[0, 0], label=labels[i])
    plt.legend()
    plt.title(title, fontsize=18)
    if not save_path is None:
        plt.savefig(save_path)
    plt.show()
//  [python]
def plt_intensity_distribution(list_datasets, labels=None, colors=['tab:blue', 'tab:green'], title='Intensity distribution', save_path=None):
    '''

    :param list_datasets: list of ND array [N*D]
    :param labels: labels of each datasets
    :param colors: color for plot
    :return:
    plt
    '''
    if labels is None:
        labels = ['set {}'.format(i) for i in len(list_datasets)]
    assert len(colors) == len(list_datasets), 'num of colors must match num of inputs'
    f, axes = plt.subplots(1, 1, figsize=(10, 5), sharex=True, squeeze=False)
    sns.utils.despine(left=True)

    colors = ['tab:blue', 'green']
    for i, col in enumerate(colors):
        ndarray = list_datasets[i]
        mean_image = np.mean(ndarray, axis=0)
        sns.distplot(mean_image.ravel(), color=col, ax=axes[0, 0], label=labels[i])
    plt.legend()
    plt.title(title, fontsize=18)
    if not save_path is None:
        plt.savefig(save_path)
    plt.show()
//  [python]
def plot(self, target_path, title=None):
        fig, ax = plt.subplots()
        print(self.read_counts)
        ax.hist(list(self.read_counts.values()), bins=25, zorder=1)

        if title is not None:
            ax.set_title(title)

        ax.set_xlabel("# Reads")
        ax.set_ylabel("# Cells")
        ax.grid(zorder=0)
        sns.despine()
        plt.tight_layout()
        plt.savefig(target_path)
        plt.close()

        fig, ax = plt.subplots()
        ax.hist(list(self.molecule_counts.values()), bins=25,zorder=1)
        ax.grid(zorder=0)
        sns.despine()
        if title is not None:
            plt.title(title)

        ax.set_xlabel("# Molecules")
        ax.set_ylabel("# Cells")
        plt.tight_layout()
        plt.savefig(target_path.replace('.png', '.molecules.png'))
        plt.close()
//  [python]
def plot(self, target_path, title=None):
        fig, ax = plt.subplots()
        print(self.read_counts)
        ax.hist(list(self.read_counts.values()), bins=25, zorder=1)

        if title is not None:
            ax.set_title(title)

        ax.set_xlabel("# Reads")
        ax.set_ylabel("# Cells")
        ax.grid(zorder=0)
        sns.utils.despine()
        plt.tight_layout()
        plt.savefig(target_path)
        plt.close()

        fig, ax = plt.subplots()
        ax.hist(list(self.molecule_counts.values()), bins=25,zorder=1)
        ax.grid(zorder=0)
        sns.utils.despine()
        if title is not None:
            plt.title(title)

        ax.set_xlabel("# Molecules")
        ax.set_ylabel("# Cells")
        plt.tight_layout()
        plt.savefig(target_path.replace('.png', '.molecules.png'))
        plt.close()
//  [python]
def scatter_LC(df, x='x', y='y', color='g', marker='o'):
    sns.set(context='paper', style='whitegrid', palette='colorblind', font='sans-serif',font_scale=1, color_codes=False, rc=None)
#    sns.JointGrid(data=df, x=x, y=y).plot(sns.regplot, sns.distplot)
    sns.regplot(data=df, x=x, y=y, fit_reg=1, color=color, marker=marker)
    
    # set
    ax = plt.gca()
    sns.despine()
    xticklabel = ax.get_xticklabels()
    yticklabel = ax.get_yticklabels()
    xlabel = ax.get_xlabel()
    ylabel = ax.get_ylabel()
    
    plt.setp(xticklabel, size=10,rotation=0, horizontalalignment='right')
    plt.setp(yticklabel, size=10,rotation=0, horizontalalignment='right')
    plt.xlabel(xlabel, size=15, rotation=0)
    plt.ylabel(ylabel, size=15, rotation=0)
//  [python]
def scatter_LC(df, x='x', y='y', color='g', marker='o'):
    sns.set(context='paper', style='whitegrid', palette='colorblind', font='sans-serif',font_scale=1, color_codes=False, rc=None)
#    sns.JointGrid(data=df, x=x, y=y).plot(sns.regplot, sns.distplot)
    sns.regplot(data=df, x=x, y=y, fit_reg=1, color=color, marker=marker)
    
    # set
    ax = plt.gca()
    sns.utils.despine()
    xticklabel = ax.get_xticklabels()
    yticklabel = ax.get_yticklabels()
    xlabel = ax.get_xlabel()
    ylabel = ax.get_ylabel()
    
    plt.setp(xticklabel, size=10,rotation=0, horizontalalignment='right')
    plt.setp(yticklabel, size=10,rotation=0, horizontalalignment='right')
    plt.xlabel(xlabel, size=15, rotation=0)
    plt.ylabel(ylabel, size=15, rotation=0)
//  [python]
def seaborn_style():
    """
    Set seaborn style for plotting figures
    """
    sns.set(style="ticks", context="paper", font_scale=1.4)
    sns.despine(trim=True)
    matplotlib.rcParams['pdf.fonttype'] = 42
    matplotlib.rcParams['ps.fonttype'] = 42
//  [python]
def seaborn_style():
    """
    Set seaborn style for plotting figures
    """
    sns.set(style="ticks", context="paper", font_scale=1.4)
    sns.utils.despine(trim=True)
    matplotlib.rcParams['pdf.fonttype'] = 42
    matplotlib.rcParams['ps.fonttype'] = 42
//  [python]
def plot_lagged_correlation(correlations, lags=None, save_fn=None,
                            title=None):

    # Get number of correlations (voxels or subjects)
    n_samples = correlations.shape[-1]
    
    # If no lags provided, infer from input correlations
    if not lags:
        lags = (correlations.shape[0] - 1) // 2
        
    # If lag is integer, get positive and negative range around zero
    if type(lags) is int:
        lags = np.arange(-lags, lags + 1)

    # Make sure lags match the input correlations
    assert len(lags) == correlations.shape[0]

    # Simple plotting
    sns.set_style('white')
    sns.set_style('ticks')
    plt.plot(correlations, alpha=.5)
    plt.xticks(np.arange(len(lags))[::len(lags) // 10],
               lags[::len(lags) // 10])
    plt.ylim(-.4, .8)
    plt.xlabel('lag (TRs)')
    plt.ylabel('auditory ISC')
    plt.title(title, loc='right', y=.95, x=.95)
    sns.despine(trim=True, offset=5)
    plt.tight_layout()
    if save_fn:
        plt.savefig(save_fn, dpi=300)
    plt.show()
//  [python]
def plot_lagged_correlation(correlations, lags=None, save_fn=None,
                            title=None):

    # Get number of correlations (voxels or subjects)
    n_samples = correlations.shape[-1]
    
    # If no lags provided, infer from input correlations
    if not lags:
        lags = (correlations.shape[0] - 1) // 2
        
    # If lag is integer, get positive and negative range around zero
    if type(lags) is int:
        lags = np.arange(-lags, lags + 1)

    # Make sure lags match the input correlations
    assert len(lags) == correlations.shape[0]

    # Simple plotting
    sns.set_style('white')
    sns.set_style('ticks')
    plt.plot(correlations, alpha=.5)
    plt.xticks(np.arange(len(lags))[::len(lags) // 10],
               lags[::len(lags) // 10])
    plt.ylim(-.4, .8)
    plt.xlabel('lag (TRs)')
    plt.ylabel('auditory ISC')
    plt.title(title, loc='right', y=.95, x=.95)
    sns.utils.despine(trim=True, offset=5)
    plt.tight_layout()
    if save_fn:
        plt.savefig(save_fn, dpi=300)
    plt.show()
//  [python]
def _generic_histogram(bars, legend_labels, title_string, pdf, ax, fig, ylabel, names, box_label, bbox_to_anchor):
    fig.legend([x[0] for x in bars[::-1]], legend_labels[::-1], bbox_to_anchor=bbox_to_anchor, frameon=True,
               title=box_label)
    ax.set_title(title_string)
    ax.set_ylabel(ylabel)
    set_ticks(names, ax)
    ax.xaxis.set_ticks(np.arange(0, len(names)) + bar_width / 2.0)
    sns.despine(top=True, right=True)
    multipage_close(pdf)
//  [python]
def _generic_histogram(bars, legend_labels, title_string, pdf, ax, fig, ylabel, names, box_label, bbox_to_anchor):
    fig.legend([x[0] for x in bars[::-1]], legend_labels[::-1], bbox_to_anchor=bbox_to_anchor, frameon=True,
               title=box_label)
    ax.set_title(title_string)
    ax.set_ylabel(ylabel)
    set_ticks(names, ax)
    ax.xaxis.set_ticks(np.arange(0, len(names)) + bar_width / 2.0)
    sns.utils.despine(top=True, right=True)
    multipage_close(pdf)
//  [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="colorblind",
    size=None,
):
    with sb.axes_style(
        "whitegrid",
        rc={
            "grid.linestyle": "dotted",
            "font.family": "serif",
            "font.serif": "Times New Roman",
        },
    ), 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=False,
            alpha=0.15,
            zorder=1,
            linewidth=0.2,
        )

        # Show the conditional means
        sb.pointplot(
            data=df,
            x=x,
            y=y,
            hue=hue,
            hue_order=hue_order,
            palette=colormap,
            dodge=0.5,
            join=False,
            markers="d",
            scale=1.1,
            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)
        print("Legend", handles, labels)

        axes.legend(
            handles,
            labels,
            title=legend_title or hue,
            handletextpad=0,
            columnspacing=1,
            loc=legend_loc,
            ncol=1,
            frameon=True,
        )
        # draw vertical line from (70,100) to (70, 250)
        for i in range(0, 14):
            axes.plot([0, 1], [i + 0.5, i + 0.5], "--", lw=0.5, color="gray")
        axes.plot([0, 1], [13.5, 13.5], "--", lw=1.5, color="gray")
        axes.plot([0, 1], [10.5, 10.5], "--", lw=1.5, color="gray")

        # axes.get_legend().remove()
        set_labels(axes, title=title, xlabel=xlabel, ylabel=ylabel, y_labels=y_labels)
        return strip_fig