jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def N_runs_noise_level_graphs(N_runs, N, imgs, beta,sep_fns,fn_labels, 
                              sigmas, 
                            #   sep_fn = separation_max, 
                              sep_param = 1000, load_data = False,
                              sname = "tiny_N_noise_level_results.npy", figname = "tiny_N_runs_noise_levels.jpg", plot_results = True):
    if not load_data:
        N_corrects = []
        for n in range(N_runs):
            X = imgs[(N*n):(N * (n+1))]
            corrects_list = plot_noise_level_graphs(N, X, beta, sep_fns,fn_labels, sigmas, sep_param = sep_param)
            N_corrects.append(corrects_list)
        N_corrects = np.array(N_corrects)
        np.save(sname, N_corrects)
    else:
        N_corrects = np.load(sname)

    if plot_results:
        mean_corrects = np.mean(N_corrects,axis=0)
        std_corrects = np.std(N_corrects, axis=0)
        # begin plot
        fig = plt.figure(figsize=(12,10))
        sns.set_theme(context='talk',font='sans-serif',font_scale=1.0)
        sns.despine(left=False,top=True, right=True, bottom=False)
        dataset = parse_sname_for_title(sname)
        plt.title(f"Memory Robustness ({dataset})",fontsize=30)
        for i in range(len(sep_fns)):
            plt.plot(sigmas, mean_corrects[:,i],label=fn_labels[i])
            plt.fill_between(sigmas, mean_corrects[:,i] - std_corrects[:,i], mean_corrects[:,i]+std_corrects[:,i],alpha=0.5)
        plt.xlabel("Noise Variance ($\sigma$)",fontsize=25)
        plt.ylabel("Retrieval Success Rate",fontsize=25)
        plt.yticks(fontsize=20)
        plt.xticks(fontsize=20)
        plt.ylim(0.5, 1)
        # if dataset == "MNIST":
        plt.legend(fontsize=25)
        plt.ylim(bottom=0)
        fig.tight_layout()
        plt.savefig(figname, format=SAVE_FORMAT)
        # plt.show()
    return N_corrects
//  [python]
def N_runs_noise_level_graphs(N_runs, N, imgs, beta,sep_fns,fn_labels, 
                              sigmas, 
                            #   sep_fn = separation_max, 
                              sep_param = 1000, load_data = False,
                              sname = "tiny_N_noise_level_results.npy", figname = "tiny_N_runs_noise_levels.jpg", plot_results = True):
    if not load_data:
        N_corrects = []
        for n in range(N_runs):
            X = imgs[(N*n):(N * (n+1))]
            corrects_list = plot_noise_level_graphs(N, X, beta, sep_fns,fn_labels, sigmas, sep_param = sep_param)
            N_corrects.append(corrects_list)
        N_corrects = np.array(N_corrects)
        np.save(sname, N_corrects)
    else:
        N_corrects = np.load(sname)

    if plot_results:
        mean_corrects = np.mean(N_corrects,axis=0)
        std_corrects = np.std(N_corrects, axis=0)
        # begin plot
        fig = plt.figure(figsize=(12,10))
        sns.set_theme(context='talk',font='sans-serif',font_scale=1.0)
        sns.utils.despine(left=False,top=True, right=True, bottom=False)
        dataset = parse_sname_for_title(sname)
        plt.title(f"Memory Robustness ({dataset})",fontsize=30)
        for i in range(len(sep_fns)):
            plt.plot(sigmas, mean_corrects[:,i],label=fn_labels[i])
            plt.fill_between(sigmas, mean_corrects[:,i] - std_corrects[:,i], mean_corrects[:,i]+std_corrects[:,i],alpha=0.5)
        plt.xlabel("Noise Variance ($\sigma$)",fontsize=25)
        plt.ylabel("Retrieval Success Rate",fontsize=25)
        plt.yticks(fontsize=20)
        plt.xticks(fontsize=20)
        plt.ylim(0.5, 1)
        # if dataset == "MNIST":
        plt.legend(fontsize=25)
        plt.ylim(bottom=0)
        fig.tight_layout()
        plt.savefig(figname, format=SAVE_FORMAT)
        # plt.show()
    return N_corrects
//  [python]
def N_runs_mask_frac_graphs(N_runs, N, imgs, beta,fs,fn_labels, mask_fracs, sep_fn = separation_max, sep_param = 1000, load_data = False,sname = "tiny_N_mask_frac_results.npy", figname = "tiny_N_runs_mask_fracs.jpg", plot_results = True, image_perturb_fn= mask_continuous_img):
    if not load_data:
        N_corrects = []
        for n in range(N_runs):
            X = imgs[(N*n):(N * (n+1))]
            corrects_list = plot_mask_frac_graphs(N, X, beta, fs, fn_labels, mask_fracs, sep_fn = sep_fn, sep_param = sep_param,image_perturb_fn= image_perturb_fn)
            N_corrects.append(corrects_list)
        N_corrects = np.array(N_corrects)
        np.save(sname, N_corrects)
    else:
        N_corrects = np.load(sname)

    if plot_results:
        mean_corrects = np.mean(N_corrects,axis=0)
        std_corrects = np.std(N_corrects, axis=0)
        # begin plot
        fig = plt.figure(figsize=(12,10))
        sns.set_theme(context='talk',font='sans-serif',font_scale=1.0)
        sns.despine(left=False,top=True, right=True, bottom=False)
        dataset = parse_sname_for_title(sname)
        plt.title(dataset + " Fraction Masked",fontsize=30)
        for i in range(len(fs)):
            plt.plot(mask_fracs, mean_corrects[:,i],label=fn_labels[i])
            plt.fill_between(mask_fracs, mean_corrects[:,i] - std_corrects[:,i], mean_corrects[:,i]+std_corrects[:,i],alpha=0.5)
        plt.xlabel("Fraction Masked",fontsize=25)
        plt.ylabel("Fraction Correctly Retrieved",fontsize=25)
        plt.yticks(fontsize=20)
        plt.xticks(fontsize=20)
        if dataset == "MNIST":
            plt.legend(fontsize=25)
        plt.ylim(bottom=0)
        fig.tight_layout()
        plt.savefig(figname, format=SAVE_FORMAT)
        plt.show()
    return N_corrects
//  [python]
def N_runs_mask_frac_graphs(N_runs, N, imgs, beta,fs,fn_labels, mask_fracs, sep_fn = separation_max, sep_param = 1000, load_data = False,sname = "tiny_N_mask_frac_results.npy", figname = "tiny_N_runs_mask_fracs.jpg", plot_results = True, image_perturb_fn= mask_continuous_img):
    if not load_data:
        N_corrects = []
        for n in range(N_runs):
            X = imgs[(N*n):(N * (n+1))]
            corrects_list = plot_mask_frac_graphs(N, X, beta, fs, fn_labels, mask_fracs, sep_fn = sep_fn, sep_param = sep_param,image_perturb_fn= image_perturb_fn)
            N_corrects.append(corrects_list)
        N_corrects = np.array(N_corrects)
        np.save(sname, N_corrects)
    else:
        N_corrects = np.load(sname)

    if plot_results:
        mean_corrects = np.mean(N_corrects,axis=0)
        std_corrects = np.std(N_corrects, axis=0)
        # begin plot
        fig = plt.figure(figsize=(12,10))
        sns.set_theme(context='talk',font='sans-serif',font_scale=1.0)
        sns.utils.despine(left=False,top=True, right=True, bottom=False)
        dataset = parse_sname_for_title(sname)
        plt.title(dataset + " Fraction Masked",fontsize=30)
        for i in range(len(fs)):
            plt.plot(mask_fracs, mean_corrects[:,i],label=fn_labels[i])
            plt.fill_between(mask_fracs, mean_corrects[:,i] - std_corrects[:,i], mean_corrects[:,i]+std_corrects[:,i],alpha=0.5)
        plt.xlabel("Fraction Masked",fontsize=25)
        plt.ylabel("Fraction Correctly Retrieved",fontsize=25)
        plt.yticks(fontsize=20)
        plt.xticks(fontsize=20)
        if dataset == "MNIST":
            plt.legend(fontsize=25)
        plt.ylim(bottom=0)
        fig.tight_layout()
        plt.savefig(figname, format=SAVE_FORMAT)
        plt.show()
    return N_corrects
//  [python]
def N_runs_capacity_graphs(N_runs, Ns, imgs, beta,fs,fn_labels, image_perturb_fn = halve_continuous_img, sep_fn = separation_max, sep_param = 1000, sigma=0.1,sname = "tiny_N_capacity_results.npy", figname = "tiny_N_runs_capacity_graph.jpg", load_data = False, plot_results = True, save_continuously=True,normalize_error_threshold = False):
    if not load_data:
        N_corrects = []
        max_N = Ns[-1]
        for n in range(N_runs):
            X = imgs[(max_N*n):(max_N * (n+1))]
            corrects_list = plot_capacity_graphs(Ns, X, beta, fs, fn_labels, image_perturb_fn=image_perturb_fn, sep_fn = sep_fn, sep_param = sep_param, sigma=sigma, normalize_error_threshold=normalize_error_threshold)
            N_corrects.append(corrects_list)
            if save_continuously:
                prelim_N_corrects = np.array(deepcopy(N_corrects))
                np.save(sname, prelim_N_corrects)
        N_corrects = np.array(N_corrects)
        np.save(sname, N_corrects)
    else:
        N_corrects = np.load(sname)
    # begin plot
    if plot_results:
        mean_corrects = np.mean(N_corrects,axis=0)
        std_corrects = np.std(N_corrects, axis=0)
        fig = plt.figure(figsize=(12,10))
        sns.set_theme(context='talk',font='sans-serif',font_scale=1.0)
        sns.despine(left=False,top=True, right=True, bottom=False)
        dataset = parse_sname_for_title(sname)
        plt.title(dataset + " Similarity Functions",fontsize=30)
        for i in range(len(fs)):
            plt.plot(Ns, mean_corrects[i,:],label=fn_labels[i])
            plt.fill_between(Ns, mean_corrects[i,:] - std_corrects[i,:], mean_corrects[i,:]+std_corrects[i,:],alpha=0.5)
        plt.xlabel("Images Stored",fontsize=25)
        plt.ylabel("Fraction Correctly Retrieved",fontsize=25)
        plt.yticks(fontsize=20)
        plt.xticks(fontsize=20)
        if dataset == "MNIST":
            plt.legend(fontsize=25)
        plt.ylim(bottom=0,top=1)
        fig.tight_layout()
        plt.savefig(figname, format=SAVE_FORMAT)
        plt.show()
    return N_corrects
//  [python]
def N_runs_capacity_graphs(N_runs, Ns, imgs, beta,fs,fn_labels, image_perturb_fn = halve_continuous_img, sep_fn = separation_max, sep_param = 1000, sigma=0.1,sname = "tiny_N_capacity_results.npy", figname = "tiny_N_runs_capacity_graph.jpg", load_data = False, plot_results = True, save_continuously=True,normalize_error_threshold = False):
    if not load_data:
        N_corrects = []
        max_N = Ns[-1]
        for n in range(N_runs):
            X = imgs[(max_N*n):(max_N * (n+1))]
            corrects_list = plot_capacity_graphs(Ns, X, beta, fs, fn_labels, image_perturb_fn=image_perturb_fn, sep_fn = sep_fn, sep_param = sep_param, sigma=sigma, normalize_error_threshold=normalize_error_threshold)
            N_corrects.append(corrects_list)
            if save_continuously:
                prelim_N_corrects = np.array(deepcopy(N_corrects))
                np.save(sname, prelim_N_corrects)
        N_corrects = np.array(N_corrects)
        np.save(sname, N_corrects)
    else:
        N_corrects = np.load(sname)
    # begin plot
    if plot_results:
        mean_corrects = np.mean(N_corrects,axis=0)
        std_corrects = np.std(N_corrects, axis=0)
        fig = plt.figure(figsize=(12,10))
        sns.set_theme(context='talk',font='sans-serif',font_scale=1.0)
        sns.utils.despine(left=False,top=True, right=True, bottom=False)
        dataset = parse_sname_for_title(sname)
        plt.title(dataset + " Similarity Functions",fontsize=30)
        for i in range(len(fs)):
            plt.plot(Ns, mean_corrects[i,:],label=fn_labels[i])
            plt.fill_between(Ns, mean_corrects[i,:] - std_corrects[i,:], mean_corrects[i,:]+std_corrects[i,:],alpha=0.5)
        plt.xlabel("Images Stored",fontsize=25)
        plt.ylabel("Fraction Correctly Retrieved",fontsize=25)
        plt.yticks(fontsize=20)
        plt.xticks(fontsize=20)
        if dataset == "MNIST":
            plt.legend(fontsize=25)
        plt.ylim(bottom=0,top=1)
        fig.tight_layout()
        plt.savefig(figname, format=SAVE_FORMAT)
        plt.show()
    return N_corrects
//  [python]
def N_runs_separation_function_graphs(N_runs, Ns, imgs, beta,sep_fns,fn_labels, f = dot_product_distance, 
                                      sep_fn = separation_max, sep_param = 1000, 
                                      load_data = False,sname = "tiny_N_runs_separation_function_results_2.npy", 
                                      figname = "tiny_N_runs_separation_functions_2.jpg", plot_results = True):
    if not load_data:
        N_corrects = []
        max_N = Ns[-1]
        for n in range(N_runs):
            X = imgs[(max_N*n):(max_N * (n+1))]

            corrects_list = plot_separation_function_graph(Ns, X, beta, sep_fns, fn_labels, f=f,sep_param=sep_param)
            N_corrects.append(corrects_list)
        N_corrects = np.array(N_corrects)
        np.save(sname, N_corrects)
    else:
        N_corrects = np.load(sname)
    if plot_results:
        mean_corrects = np.mean(N_corrects,axis=0)
        std_corrects = np.std(N_corrects, axis=0)
        # begin plot
        fig = plt.figure(figsize=(12,10))
        sns.set_theme(context='talk',font='sans-serif',font_scale=1.0)
        sns.despine(left=False,top=True, right=True, bottom=False)
        dataset = parse_sname_for_title(sname)
        plt.title(f"Memory Capacity ({dataset})", fontsize=30)
        xs = np.arange(0, len(Ns))
        for i in range(len(sep_fns)):
            print(mean_corrects[i,:])
            plt.plot(Ns, mean_corrects[i,:],label=fn_labels[i])
            plt.fill_between(Ns, mean_corrects[i,:] - std_corrects[i,:], mean_corrects[i,:]+std_corrects[i,:],alpha=0.5)
        plt.xlabel("Number of Memory Patterns",fontsize=25)
        plt.ylabel("Retrieval Success Rate",fontsize=25)
        plt.yticks(fontsize=20)
        plt.xticks(fontsize=20)

        plt.legend(fontsize=25)
        if dataset_str == "cifar_10_":
            plt.ylim(bottom=0.2,top=0.8)
        elif dataset_str == "imagenet_":
            plt.ylim(bottom=0,top=0.8)
        else:
            plt.ylim(bottom=0,top=1)
        
        fig.tight_layout()
        plt.savefig(figname, format=SAVE_FORMAT)
        plt.show()
    return N_corrects
//  [python]
def N_runs_separation_function_graphs(N_runs, Ns, imgs, beta,sep_fns,fn_labels, f = dot_product_distance, 
                                      sep_fn = separation_max, sep_param = 1000, 
                                      load_data = False,sname = "tiny_N_runs_separation_function_results_2.npy", 
                                      figname = "tiny_N_runs_separation_functions_2.jpg", plot_results = True):
    if not load_data:
        N_corrects = []
        max_N = Ns[-1]
        for n in range(N_runs):
            X = imgs[(max_N*n):(max_N * (n+1))]

            corrects_list = plot_separation_function_graph(Ns, X, beta, sep_fns, fn_labels, f=f,sep_param=sep_param)
            N_corrects.append(corrects_list)
        N_corrects = np.array(N_corrects)
        np.save(sname, N_corrects)
    else:
        N_corrects = np.load(sname)
    if plot_results:
        mean_corrects = np.mean(N_corrects,axis=0)
        std_corrects = np.std(N_corrects, axis=0)
        # begin plot
        fig = plt.figure(figsize=(12,10))
        sns.set_theme(context='talk',font='sans-serif',font_scale=1.0)
        sns.utils.despine(left=False,top=True, right=True, bottom=False)
        dataset = parse_sname_for_title(sname)
        plt.title(f"Memory Capacity ({dataset})", fontsize=30)
        xs = np.arange(0, len(Ns))
        for i in range(len(sep_fns)):
            print(mean_corrects[i,:])
            plt.plot(Ns, mean_corrects[i,:],label=fn_labels[i])
            plt.fill_between(Ns, mean_corrects[i,:] - std_corrects[i,:], mean_corrects[i,:]+std_corrects[i,:],alpha=0.5)
        plt.xlabel("Number of Memory Patterns",fontsize=25)
        plt.ylabel("Retrieval Success Rate",fontsize=25)
        plt.yticks(fontsize=20)
        plt.xticks(fontsize=20)

        plt.legend(fontsize=25)
        if dataset_str == "cifar_10_":
            plt.ylim(bottom=0.2,top=0.8)
        elif dataset_str == "imagenet_":
            plt.ylim(bottom=0,top=0.8)
        else:
            plt.ylim(bottom=0,top=1)
        
        fig.tight_layout()
        plt.savefig(figname, format=SAVE_FORMAT)
        plt.show()
    return N_corrects
//  [python]
def plot_hists(subjects, axes, label_last=1, ymax=350):

    bins = np.linspace(-2, 2, 20)

    for subj, ax in zip(subjects, axes):

        exp = dict(pc="dots", ti="sticks")[subj[:2]]

        res_fname = "decoding_analysis/{}_{}_ifs.pkz".format(subj, exp)
        res = moss.load_pkl(res_fname)
        prefs = res.prefs
        pctiles = res.pref_pctiles

        cmap = get_colormap(exp)

        plot_prefs = [prefs[pctiles < 10],
                      prefs[pctiles > 90],
                      prefs[(pctiles >= 10) & (pctiles <= 90)]]

        ax.hist(plot_prefs, histtype="barstacked", rwidth=1,
                color=[cmap(.01), cmap(.99), ".9"], bins=bins)

        ax.set(xlim=(-2, 2),
               xticks=[-2, -1, 0, 1, 2],
               xticklabels=[],
               yticks=[],
               ylim=(0, ymax))

    for ax in axes[-label_last:]:
        ax.set_xlabel("Context\npreference", labelpad=2, fontsize=7)
        ax.set(xticklabels=[-2, -1, 0, 1, 2])

    for ax in axes:
        sns.despine(ax=ax, left=True)
//  [python]
def plot_hists(subjects, axes, label_last=1, ymax=350):

    bins = np.linspace(-2, 2, 20)

    for subj, ax in zip(subjects, axes):

        exp = dict(pc="dots", ti="sticks")[subj[:2]]

        res_fname = "decoding_analysis/{}_{}_ifs.pkz".format(subj, exp)
        res = moss.load_pkl(res_fname)
        prefs = res.prefs
        pctiles = res.pref_pctiles

        cmap = get_colormap(exp)

        plot_prefs = [prefs[pctiles < 10],
                      prefs[pctiles > 90],
                      prefs[(pctiles >= 10) & (pctiles <= 90)]]

        ax.hist(plot_prefs, histtype="barstacked", rwidth=1,
                color=[cmap(.01), cmap(.99), ".9"], bins=bins)

        ax.set(xlim=(-2, 2),
               xticks=[-2, -1, 0, 1, 2],
               xticklabels=[],
               yticks=[],
               ylim=(0, ymax))

    for ax in axes[-label_last:]:
        ax.set_xlabel("Context\npreference", labelpad=2, fontsize=7)
        ax.set(xticklabels=[-2, -1, 0, 1, 2])

    for ax in axes:
        sns.utils.despine(ax=ax, left=True)
//  [python]
sns.set_context("notebook")

for track in read_gpx_file("example1.gpx"):
    for i, segment in enumerate(track["segments"]):
        # Plot elevation as function of distance:
        fig1, _ = plot_filled(
            track, segment, xvar="Distance / km", yvar="elevation", zvar="hr"
        )
        sns.despine(fig=fig1)
        # Plot elevation as function of elapsed time:
        fig2, _ = plot_filled(
            track,
            segment,
            xvar="elapsed-time",
            yvar="elevation",
            zvar="hr",
            cmap="vlag",
        )
        sns.despine(fig=fig2)
//  [python]
sns.set_context("notebook")

for track in read_gpx_file("example1.gpx"):
    for i, segment in enumerate(track["segments"]):
        # Plot elevation as function of distance:
        fig1, _ = plot_filled(
            track, segment, xvar="Distance / km", yvar="elevation", zvar="hr"
        )
        sns.utils.despine(fig=fig1)
        # Plot elevation as function of elapsed time:
        fig2, _ = plot_filled(
            track,
            segment,
            xvar="elapsed-time",
            yvar="elevation",
            zvar="hr",
            cmap="vlag",
        )
        sns.utils.despine(fig=fig2)
//  [python]
def plot_cluster_error(ax):

    res_ftemp = "spatial_analysis/{}_{}_ifs.pkz"
    for exp in ["dots", "sticks"]:

        subjects = get_subject_order(exp)
        color = get_colormap(exp, as_cmap=False)[20]

        errs = []
        for subj in subjects:

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

            norm = res.null.mean()
            errs.append(res.real / norm)

        errs = np.vstack(errs)
        mean = errs.mean(axis=0)
        ax.plot(x, mean, color=color, lw=2)
        sem = stats.sem(errs, axis=0)
        ax.fill_between(x, mean - sem, mean + sem, alpha=.2, color=color)


    ax.axhline(y=1, lw=1, dashes=[5, 2],
               color=".5", zorder=0,
               xmin=.02, xmax=.98)

    ax.set(xlim=(0, 42),
           ylim=(.55, 1.45),
           yticks=[.6, .8, 1, 1.2, 1.4],
           xticks=[0, 10, 20, 30, 40],
           xlabel="Neighborhood radius (mm)",
           ylabel="Normalized error")

    sns.despine(ax=ax, trim=True)
//  [python]
def plot_cluster_error(ax):

    res_ftemp = "spatial_analysis/{}_{}_ifs.pkz"
    for exp in ["dots", "sticks"]:

        subjects = get_subject_order(exp)
        color = get_colormap(exp, as_cmap=False)[20]

        errs = []
        for subj in subjects:

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

            norm = res.null.mean()
            errs.append(res.real / norm)

        errs = np.vstack(errs)
        mean = errs.mean(axis=0)
        ax.plot(x, mean, color=color, lw=2)
        sem = stats.sem(errs, axis=0)
        ax.fill_between(x, mean - sem, mean + sem, alpha=.2, color=color)


    ax.axhline(y=1, lw=1, dashes=[5, 2],
               color=".5", zorder=0,
               xmin=.02, xmax=.98)

    ax.set(xlim=(0, 42),
           ylim=(.55, 1.45),
           yticks=[.6, .8, 1, 1.2, 1.4],
           xticks=[0, 10, 20, 30, 40],
           xlabel="Neighborhood radius (mm)",
           ylabel="Normalized error")

    sns.utils.despine(ax=ax, trim=True)
//  [python]
def plot_thr_weather(args):
    df_down_udp = concat_df(args.src_folder, UDP_DOWN, [BANDWIDTH])
    df_down_udp = df_down_udp.resample('H').mean()
    df_down_udp.index = df_down_udp.index.tz_localize('UTC')
    print(df_down_udp.head())

    df_weather = combine_csvs(glob.glob(os.path.join(args.src_weather, '*.csv')), 4)
    df_weather.index = pd.to_datetime(df_weather.index).tz_localize(tz.tzlocal())
    df_weather = df_weather[[PRECIP]]
    
    df_merged = df_down_udp.merge(df_weather, left_index=True, right_index=True, how='inner').drop_duplicates()
    #print(df_merged.head())
    #print(df_merged[df_merged.columns[1]].count())

    if args.save:
        df_merged.to_csv("combined.csv", encoding='utf-8-sig')

    
    #fig, ax = plt.subplots(figsize=(3.5,2))
    fig, ax = plt.subplots(figsize=(7.16,5))
    #sns.scatterplot(x=df_merged.iloc[:, 1], y=df_merged.jitter_ms, ax=ax)
    sns.scatterplot(x=df_merged.index, y=df_merged.iloc[:, 1], ax=ax)
    sns.despine()

    for label in ax.get_xticklabels():
        label.set_rotation(45)
        label.set_ha('right')

    #ax.set_xlabel("Day of Month (2022)")
    #ax.set_ylabel("Jitter (m)")
    if args.name:
        ax.set_title(args.name)

    plt.savefig(f'{args.filename}.eps', format='eps', bbox_inches='tight')
//  [python]
def plot_thr_weather(args):
    df_down_udp = concat_df(args.src_folder, UDP_DOWN, [BANDWIDTH])
    df_down_udp = df_down_udp.resample('H').mean()
    df_down_udp.index = df_down_udp.index.tz_localize('UTC')
    print(df_down_udp.head())

    df_weather = combine_csvs(glob.glob(os.path.join(args.src_weather, '*.csv')), 4)
    df_weather.index = pd.to_datetime(df_weather.index).tz_localize(tz.tzlocal())
    df_weather = df_weather[[PRECIP]]
    
    df_merged = df_down_udp.merge(df_weather, left_index=True, right_index=True, how='inner').drop_duplicates()
    #print(df_merged.head())
    #print(df_merged[df_merged.columns[1]].count())

    if args.save:
        df_merged.to_csv("combined.csv", encoding='utf-8-sig')

    
    #fig, ax = plt.subplots(figsize=(3.5,2))
    fig, ax = plt.subplots(figsize=(7.16,5))
    #sns.scatterplot(x=df_merged.iloc[:, 1], y=df_merged.jitter_ms, ax=ax)
    sns.scatterplot(x=df_merged.index, y=df_merged.iloc[:, 1], ax=ax)
    sns.utils.despine()

    for label in ax.get_xticklabels():
        label.set_rotation(45)
        label.set_ha('right')

    #ax.set_xlabel("Day of Month (2022)")
    #ax.set_ylabel("Jitter (m)")
    if args.name:
        ax.set_title(args.name)

    plt.savefig(f'{args.filename}.eps', format='eps', bbox_inches='tight')
//  [python]
def plot_MASH_dendrogram(Mdb, Cdb, linkage, threshold=False, plot_dir=False):
    '''
    Make a dendrogram of the primary clustering

    Args:
        Mdb: DataFrame of Mash comparison results; make sure loaded not as categories
        Cdb: DataFrame of Clustering results
        linkage: Result of scipy.cluster.hierarchy.linkage
        threshold (optional): Line to plot on x-axis
        plot_dir (optional): Location to store plot

    Returns:
        Makes and shows plot
    '''
    sns.set_style('white',{'axes.grid': False})

    if Mdb['genome1'].dtype.name == 'category':
        logging.error("WARNING: Primary dendrogram labels may be shuffled! Load as csv to prevent this")

    db = Mdb.pivot(index="genome1", columns="genome2", values="similarity")
    names = list(db.columns)
    name2cluster = Cdb.set_index('genome')['primary_cluster'].to_dict()
    name2color = gen_color_dictionary(names, name2cluster)

    # Make the dendrogram
    g = fancy_dendrogram(linkage,names,name2color,threshold=threshold)
    plt.title('MASH clustering')
    plt.xlabel('MASH Average Nucleotide Identity (ANI)')

    #plt.xlim([0,.4])

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

    # Adjust the figure size
    fig = plt.gcf()
    fig.set_size_inches(10,_x_fig_size(len(names),factor=.2))
    plt.subplots_adjust(left=0.3)

    # Adjust the x labels
    plt.tick_params(axis='both', which='major', labelsize=8)
    axes = plt.gca()
    labels = axes.xaxis.get_majorticklocs()
    for i, label in enumerate(labels):
        labels[i] = float("{0:.2f}".format((1 - float(label)) * 100))
    axes.set_xticklabels(labels)

    # Add cluster to the y axis
    g2c = Cdb.set_index('genome')['secondary_cluster'].to_dict()
    axes = plt.gca()
    labels = [item.get_text() for item in axes.get_yticklabels()]
    for i, label in enumerate(labels):
        labels[i] = "{0} ({1})".format(label, g2c[label])
    axes.set_yticklabels(labels)

    # Save the figure
    if plot_dir != None:
        plt.savefig(os.path.join(plot_dir, 'Primary_clustering_dendrogram.pdf'),\
            format="pdf", transparent=True, bbox_inches='tight')
    plt.show()
    plt.close('all')
//  [python]
def plot_MASH_dendrogram(Mdb, Cdb, linkage, threshold=False, plot_dir=False):
    '''
    Make a dendrogram of the primary clustering

    Args:
        Mdb: DataFrame of Mash comparison results; make sure loaded not as categories
        Cdb: DataFrame of Clustering results
        linkage: Result of scipy.cluster.hierarchy.linkage
        threshold (optional): Line to plot on x-axis
        plot_dir (optional): Location to store plot

    Returns:
        Makes and shows plot
    '''
    sns.set_style('white',{'axes.grid': False})

    if Mdb['genome1'].dtype.name == 'category':
        logging.error("WARNING: Primary dendrogram labels may be shuffled! Load as csv to prevent this")

    db = Mdb.pivot(index="genome1", columns="genome2", values="similarity")
    names = list(db.columns)
    name2cluster = Cdb.set_index('genome')['primary_cluster'].to_dict()
    name2color = gen_color_dictionary(names, name2cluster)

    # Make the dendrogram
    g = fancy_dendrogram(linkage,names,name2color,threshold=threshold)
    plt.title('MASH clustering')
    plt.xlabel('MASH Average Nucleotide Identity (ANI)')

    #plt.xlim([0,.4])

    sns.utils.despine(left=True,top=True,right=True,bottom=False)

    # Adjust the figure size
    fig = plt.gcf()
    fig.set_size_inches(10,_x_fig_size(len(names),factor=.2))
    plt.subplots_adjust(left=0.3)

    # Adjust the x labels
    plt.tick_params(axis='both', which='major', labelsize=8)
    axes = plt.gca()
    labels = axes.xaxis.get_majorticklocs()
    for i, label in enumerate(labels):
        labels[i] = float("{0:.2f}".format((1 - float(label)) * 100))
    axes.set_xticklabels(labels)

    # Add cluster to the y axis
    g2c = Cdb.set_index('genome')['secondary_cluster'].to_dict()
    axes = plt.gca()
    labels = [item.get_text() for item in axes.get_yticklabels()]
    for i, label in enumerate(labels):
        labels[i] = "{0} ({1})".format(label, g2c[label])
    axes.set_yticklabels(labels)

    # Save the figure
    if plot_dir != None:
        plt.savefig(os.path.join(plot_dir, 'Primary_clustering_dendrogram.pdf'),\
            format="pdf", transparent=True, bbox_inches='tight')
    plt.show()
    plt.close('all')
//  [python]
def plot_spatial(
        adata,
        annotation,
        ax: Axes,
        spot_size: float,
        palette=None,
        title: str = ""
):
    """
    Scatter plot in spatial coordinates.

    Parameters:
        - adata (AnnData): Annotated data object which represents the sample
        - annotation (str): adata.obs column used for grouping
        - ax (Axes): Axes object used for plotting
        - spot_size (int): Size of the dot that represents a cell. We are passing it as a diameter of the spot, while
                the plotting library uses radius therefore it is multiplied by 0.5
        - palette (dict): Dictionary that represents a mapping between annotation categories and colors
        - title (str): Title of the figure

    """
    s = spot_size * 0.2
    data = adata
    ax = sns.scatterplot(
        data=data.obs, hue=annotation, x=data.obsm['spatial'][:, 0], y=data.obsm['spatial'][:, 1],
        ax=ax, s=s, linewidth=0, palette=palette, marker='.'
    )
    ax.set(yticklabels=[], xticklabels=[], title=title)
    ax.tick_params(bottom=False, left=False)
    ax.set_aspect("equal")
    sns.despine(bottom=True, left=True, ax=ax)
//  [python]
def plot_spatial(
        adata,
        annotation,
        ax: Axes,
        spot_size: float,
        palette=None,
        title: str = ""
):
    """
    Scatter plot in spatial coordinates.

    Parameters:
        - adata (AnnData): Annotated data object which represents the sample
        - annotation (str): adata.obs column used for grouping
        - ax (Axes): Axes object used for plotting
        - spot_size (int): Size of the dot that represents a cell. We are passing it as a diameter of the spot, while
                the plotting library uses radius therefore it is multiplied by 0.5
        - palette (dict): Dictionary that represents a mapping between annotation categories and colors
        - title (str): Title of the figure

    """
    s = spot_size * 0.2
    data = adata
    ax = sns.scatterplot(
        data=data.obs, hue=annotation, x=data.obsm['spatial'][:, 0], y=data.obsm['spatial'][:, 1],
        ax=ax, s=s, linewidth=0, palette=palette, marker='.'
    )
    ax.set(yticklabels=[], xticklabels=[], title=title)
    ax.tick_params(bottom=False, left=False)
    ax.set_aspect("equal")
    sns.utils.despine(bottom=True, left=True, ax=ax)
//  [python]
def plot_region_percent_cli(df_survey_range: pd.DataFrame,
                                locator: str = "month",
                                interval: int = 1) -> Any:
        """Plot the CLI (Covid-like illness) from the results
        of a region.

        :param df_survey_range: the results from the survey
        :param locator: can be "month" or "day", to define the
                        location of ticks in the plot for the dates
        :param interval: interval to show the date labels in the plot
        """
        plt.plot(df_survey_range["survey_date"],
                 df_survey_range.percent_cli * 100.0, color="red", lw=0.8,
                 marker='o', markersize=5, markerfacecolor='w')
        ax = plt.gca()
        ax.fill_between(df_survey_range["survey_date"],
                        df_survey_range.percent_cli_95_upper_ci,
                        df_survey_range.percent_cli_95_lower_ci,
                        alpha=0.2, lw=1.5, color="C1")

        loc = mdates.MonthLocator(interval=interval)
        formatter = mdates.DateFormatter(fmt="%b %Y")

        if locator == "day":
            loc = mdates.DayLocator(interval=interval)
            formatter = mdates.DateFormatter(fmt="%d %b %Y")

        ax.xaxis.set_major_locator(loc)
        ax.xaxis.set_major_formatter(formatter)
        ax.figure.autofmt_xdate(rotation=90, ha='center')

        plt.grid(axis="both", which="major", linestyle="--", alpha=0.4)

        plt.xlabel("Dates")
        plt.ylabel("Weighted percentage w/ COVID-like illness")

        plt.title("Facebook symptoms survey")
        sns.despine()
        plt.tight_layout()
        return ax
//  [python]
def plot_region_percent_cli(df_survey_range: pd.DataFrame,
                                locator: str = "month",
                                interval: int = 1) -> Any:
        """Plot the CLI (Covid-like illness) from the results
        of a region.

        :param df_survey_range: the results from the survey
        :param locator: can be "month" or "day", to define the
                        location of ticks in the plot for the dates
        :param interval: interval to show the date labels in the plot
        """
        plt.plot(df_survey_range["survey_date"],
                 df_survey_range.percent_cli * 100.0, color="red", lw=0.8,
                 marker='o', markersize=5, markerfacecolor='w')
        ax = plt.gca()
        ax.fill_between(df_survey_range["survey_date"],
                        df_survey_range.percent_cli_95_upper_ci,
                        df_survey_range.percent_cli_95_lower_ci,
                        alpha=0.2, lw=1.5, color="C1")

        loc = mdates.MonthLocator(interval=interval)
        formatter = mdates.DateFormatter(fmt="%b %Y")

        if locator == "day":
            loc = mdates.DayLocator(interval=interval)
            formatter = mdates.DateFormatter(fmt="%d %b %Y")

        ax.xaxis.set_major_locator(loc)
        ax.xaxis.set_major_formatter(formatter)
        ax.figure.autofmt_xdate(rotation=90, ha='center')

        plt.grid(axis="both", which="major", linestyle="--", alpha=0.4)

        plt.xlabel("Dates")
        plt.ylabel("Weighted percentage w/ COVID-like illness")

        plt.title("Facebook symptoms survey")
        sns.utils.despine()
        plt.tight_layout()
        return ax
//  [python]
def plot_mu_p(mu, sigma):
    xs = np.linspace(mu - sigma * 4, mu + sigma * 4, 1000)
    ys = norm(loc=mu, scale=sigma).pdf(xs)

    fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 4), sharey=True)
    ax[0].plot(xs, ys)
    ax[0].set_xlabel(r"$\mu$")
    ax[0].set_ylabel("PDF")
    ax[0].axvline(x=0, color="red")
    ax[0].set_title("Gaussian Space")
    ax[1].plot(expit(xs), ys)
    ax[1].set_xlim(0, 1)
    ax[1].set_xlabel(r"p = invlogit($\mu$)")
    ax[1].set_title("Bounded space")
    sns.despine()
    plt.show()
//  [python]
def plot_mu_p(mu, sigma):
    xs = np.linspace(mu - sigma * 4, mu + sigma * 4, 1000)
    ys = norm(loc=mu, scale=sigma).pdf(xs)

    fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 4), sharey=True)
    ax[0].plot(xs, ys)
    ax[0].set_xlabel(r"$\mu$")
    ax[0].set_ylabel("PDF")
    ax[0].axvline(x=0, color="red")
    ax[0].set_title("Gaussian Space")
    ax[1].plot(expit(xs), ys)
    ax[1].set_xlim(0, 1)
    ax[1].set_xlabel(r"p = invlogit($\mu$)")
    ax[1].set_title("Bounded space")
    sns.utils.despine()
    plt.show()
//  [python]
def plot_plane_stats(stats, out_dir):
    sns.set_style("ticks")
    for type, type_stats in stats.items():
        plt.figure()
        plt.suptitle(type)
        # for i, sname in enumerate(sorted(type_stats.keys())):
        for i, sname in enumerate(type_stats.keys()):
            data = type_stats[sname]
            plt.subplot(2,3,i+1)
            plt.hist(data, STAT_HIST_BINS[sname], **STAT_HIST_KWARGS.get(sname, {}), label='hist.', log=True)
            plt.hist(data, STAT_HIST_BINS[sname], **STAT_HIST_KWARGS.get(sname, {}), cumulative=-1, histtype='step', label='c.hist.', log=True)
            plt.xlabel(sname)
            plt.ylabel('# Planes')
            # plt.ylim([0,300])
            if sname in STAT_HIST_XTICKS:
                plt.xticks(STAT_HIST_XTICKS[sname])
        plt.legend(bbox_to_anchor=(1.8, 1.05))
        sns.despine()
        plt.tight_layout()
        plt.savefig(osp.join(out_dir, '{}.pdf'.format(type)))
        plt.close()
//  [python]
def plot_plane_stats(stats, out_dir):
    sns.set_style("ticks")
    for type, type_stats in stats.items():
        plt.figure()
        plt.suptitle(type)
        # for i, sname in enumerate(sorted(type_stats.keys())):
        for i, sname in enumerate(type_stats.keys()):
            data = type_stats[sname]
            plt.subplot(2,3,i+1)
            plt.hist(data, STAT_HIST_BINS[sname], **STAT_HIST_KWARGS.get(sname, {}), label='hist.', log=True)
            plt.hist(data, STAT_HIST_BINS[sname], **STAT_HIST_KWARGS.get(sname, {}), cumulative=-1, histtype='step', label='c.hist.', log=True)
            plt.xlabel(sname)
            plt.ylabel('# Planes')
            # plt.ylim([0,300])
            if sname in STAT_HIST_XTICKS:
                plt.xticks(STAT_HIST_XTICKS[sname])
        plt.legend(bbox_to_anchor=(1.8, 1.05))
        sns.utils.despine()
        plt.tight_layout()
        plt.savefig(osp.join(out_dir, '{}.pdf'.format(type)))
        plt.close()
//  [python]
def histogram_violin_plots(data, axes, file_name=None):
    # histogram
    sns.distplot(data, ax=axes[0], axlabel="")
    sns.violinplot(data, ax=axes[1], inner="quartile", scale="count")
    sns.despine(left=True)
//  [python]
def histogram_violin_plots(data, axes, file_name=None):
    # histogram
    sns.distplot(data, ax=axes[0], axlabel="")
    sns.violinplot(data, ax=axes[1], inner="quartile", scale="count")
    sns.utils.despine(left=True)
//  [python]
def plot(self, target_path, title=None):
        df = self.get_df()  # ,'UnmappedReads']]

        df['mq'].plot.bar(figsize=(10, 4))
        ax = plt.gca()
        ax.set_xlabel('Mapping quality')
        ax.set_ylabel('Frequency (reads)')

        if title is not None:
            plt.title(title)
        plt.tight_layout()
        plt.savefig(target_path)

        ax.set_yscale('log')
        sns.despine()
        plt.tight_layout()
        plt.savefig(target_path.replace('.png', '.log.png'))

        plt.close()
//  [python]
def plot(self, target_path, title=None):
        df = self.get_df()  # ,'UnmappedReads']]

        df['mq'].plot.bar(figsize=(10, 4))
        ax = plt.gca()
        ax.set_xlabel('Mapping quality')
        ax.set_ylabel('Frequency (reads)')

        if title is not None:
            plt.title(title)
        plt.tight_layout()
        plt.savefig(target_path)

        ax.set_yscale('log')
        sns.utils.despine()
        plt.tight_layout()
        plt.savefig(target_path.replace('.png', '.log.png'))

        plt.close()
//  [python]
def plot_line_stats(stats, out_dir):
    labels = [k for k in stats.keys() if not 'invalid' in k]
    counts = [stats[l] for l in labels]
    idx = np.argsort(counts)[::-1]
    labels = [labels[i] for i in idx]
    counts = [counts[i] for i in idx]
    sns.set_style("ticks")
    plt.figure()
    ax = plt.gca()
    bar_plot = ax.bar(range(len(labels)), counts, align='center')
    autolabel_bar(ax, bar_plot, counts)
    ax.set_xlabel('Plane Labels')
    ax.set_ylabel('# Lines')
    ax.set_xticks(range(len(labels)))
    xtick_labels = []
    for c in labels:
        if len(c) == 1:
            l = next(iter(c))
            xtick_labels.append(l+'-'+l)
        else:
            xtick_labels.append('-'.join(c))
    ax.set_xticklabels(xtick_labels, rotation=45, ha='right')
    ax.set_ylim([0, np.max(counts)*1.5])

    sns.despine()
    plt.tight_layout()

    plt.savefig(osp.join(out_dir, 'lines_stats.pdf'))
    plt.close()
//  [python]
def plot_line_stats(stats, out_dir):
    labels = [k for k in stats.keys() if not 'invalid' in k]
    counts = [stats[l] for l in labels]
    idx = np.argsort(counts)[::-1]
    labels = [labels[i] for i in idx]
    counts = [counts[i] for i in idx]
    sns.set_style("ticks")
    plt.figure()
    ax = plt.gca()
    bar_plot = ax.bar(range(len(labels)), counts, align='center')
    autolabel_bar(ax, bar_plot, counts)
    ax.set_xlabel('Plane Labels')
    ax.set_ylabel('# Lines')
    ax.set_xticks(range(len(labels)))
    xtick_labels = []
    for c in labels:
        if len(c) == 1:
            l = next(iter(c))
            xtick_labels.append(l+'-'+l)
        else:
            xtick_labels.append('-'.join(c))
    ax.set_xticklabels(xtick_labels, rotation=45, ha='right')
    ax.set_ylim([0, np.max(counts)*1.5])

    sns.utils.despine()
    plt.tight_layout()

    plt.savefig(osp.join(out_dir, 'lines_stats.pdf'))
    plt.close()
//  [python]
def scatter_plot(data, col1, col2, file_name=None):
    sns.regplot(x=col1, y=col2, data=data, fit_reg=False)
    sns.despine(left=True)
//  [python]
def scatter_plot(data, col1, col2, file_name=None):
    sns.regplot(x=col1, y=col2, data=data, fit_reg=False)
    sns.utils.despine(left=True)
//  [python]
def bar_plot(data, col, hue=None, file_name=None):
    sns.countplot(col, hue=hue, data=data.sort_values(col))
    sns.despine(left=True)

    subplots = [
        x for x in plt.gcf().get_children() if isinstance(x, matplotlib.axes.Subplot)
    ]
    for plot in subplots:
        rectangles = [
            x
            for x in plot.get_children()
            if isinstance(x, matplotlib.patches.Rectangle)
        ]
    autolabel(rectangles)
//  [python]
def bar_plot(data, col, hue=None, file_name=None):
    sns.countplot(col, hue=hue, data=data.sort_values(col))
    sns.utils.despine(left=True)

    subplots = [
        x for x in plt.gcf().get_children() if isinstance(x, matplotlib.axes.Subplot)
    ]
    for plot in subplots:
        rectangles = [
            x
            for x in plot.get_children()
            if isinstance(x, matplotlib.patches.Rectangle)
        ]
    autolabel(rectangles)
//  [python]
def save_qq(fqn: str, arr: np.ndarray):
    scatter_options = dict(
        marker="+",
        markersize=15,
        markerfacecolor="none",
        markeredgecolor="black",
        markeredgewidth=1.25,
        linestyle="none",
        zorder=5,
        label="Observations",
    )

    line_options = dict(
        color="#6184ff", linewidth=3, zorder=1, label="Best Fit", alpha=1
    )

    fig, ax = pyplot.subplots(figsize=(8, 8))
    fig = probscale.probplot(
        arr,
        ax=ax,
        plottype="pp",
        bestfit=True,
        estimate_ci=True,
        line_kws=line_options,
        scatter_kws=scatter_options,
        problabel="Percentile",
    )
    # ax.legend(loc="lower right")
    # ax.set_ylim(bottom=-2, top=4)
    seaborn.despine(fig)
    plt.savefig(fqn, pad_inches=0, bbox_inches="tight")
//  [python]
def save_qq(fqn: str, arr: np.ndarray):
    scatter_options = dict(
        marker="+",
        markersize=15,
        markerfacecolor="none",
        markeredgecolor="black",
        markeredgewidth=1.25,
        linestyle="none",
        zorder=5,
        label="Observations",
    )

    line_options = dict(
        color="#6184ff", linewidth=3, zorder=1, label="Best Fit", alpha=1
    )

    fig, ax = pyplot.subplots(figsize=(8, 8))
    fig = probscale.probplot(
        arr,
        ax=ax,
        plottype="pp",
        bestfit=True,
        estimate_ci=True,
        line_kws=line_options,
        scatter_kws=scatter_options,
        problabel="Percentile",
    )
    # ax.legend(loc="lower right")
    # ax.set_ylim(bottom=-2, top=4)
    seaborn.utils.despine(fig)
    plt.savefig(fqn, pad_inches=0, bbox_inches="tight")
//  [python]
def hist_single_vs_pooled_diff(diff_from_singles, diff_from_singles_scaled,
                               color=None, title='', nbins=50, hist_kws=None):
    """Plot a histogram of both the original difference difference of psi
    scores from the pooled to the singles, and the scaled difference

    """
    hist_kws = {} if hist_kws is None else hist_kws

    fig, axes = plt.subplots(ncols=2, figsize=(8, 4))
    dfs = (diff_from_singles, diff_from_singles_scaled)
    names = ('total_diff', 'scaled_diff')

    for ax, df, name in zip(axes, dfs, names):
        vmin = df.min().min()
        vmax = df.max().max()
        ax.hist(df.values.flat, bins=np.linspace(vmin, vmax, nbins),
                color=color, edgecolor='white', linewidth=0.5, **hist_kws)
        ax.set_title(title)
        # ax.set_title('{}, {}'.format(celltype, name))
        ax.grid(which='y', color='white')
    sns.despine()
//  [python]
def hist_single_vs_pooled_diff(diff_from_singles, diff_from_singles_scaled,
                               color=None, title='', nbins=50, hist_kws=None):
    """Plot a histogram of both the original difference difference of psi
    scores from the pooled to the singles, and the scaled difference

    """
    hist_kws = {} if hist_kws is None else hist_kws

    fig, axes = plt.subplots(ncols=2, figsize=(8, 4))
    dfs = (diff_from_singles, diff_from_singles_scaled)
    names = ('total_diff', 'scaled_diff')

    for ax, df, name in zip(axes, dfs, names):
        vmin = df.min().min()
        vmax = df.max().max()
        ax.hist(df.values.flat, bins=np.linspace(vmin, vmax, nbins),
                color=color, edgecolor='white', linewidth=0.5, **hist_kws)
        ax.set_title(title)
        # ax.set_title('{}, {}'.format(celltype, name))
        ax.grid(which='y', color='white')
    sns.utils.despine()
//  [python]
def heatmap(data, file_name=None):
    cmap = "BuGn" if (data.values >= 0).all() else "coolwarm"
    sns.heatmap(data=data, annot=True, fmt="d", cmap=cmap)
    sns.despine(left=True)
//  [python]
def heatmap(data, file_name=None):
    cmap = "BuGn" if (data.values >= 0).all() else "coolwarm"
    sns.heatmap(data=data, annot=True, fmt="d", cmap=cmap)
    sns.utils.despine(left=True)
//  [python]
def bar_box_violin_dot_plots(data, category_col, numeric_col, axes, file_name=None):
    sns.barplot(category_col, numeric_col, data=data, ax=axes[0])
    sns.boxplot(
        category_col, numeric_col, data=data[data[numeric_col].notnull()], ax=axes[2]
    )
    sns.violinplot(
        category_col,
        numeric_col,
        data=data,
        kind="violin",
        inner="quartile",
        scale="count",
        split=True,
        ax=axes[3],
    )
    sns.stripplot(category_col, numeric_col, data=data, jitter=True, ax=axes[1])
    sns.despine(left=True)
//  [python]
def bar_box_violin_dot_plots(data, category_col, numeric_col, axes, file_name=None):
    sns.barplot(category_col, numeric_col, data=data, ax=axes[0])
    sns.boxplot(
        category_col, numeric_col, data=data[data[numeric_col].notnull()], ax=axes[2]
    )
    sns.violinplot(
        category_col,
        numeric_col,
        data=data,
        kind="violin",
        inner="quartile",
        scale="count",
        split=True,
        ax=axes[3],
    )
    sns.stripplot(category_col, numeric_col, data=data, jitter=True, ax=axes[1])
    sns.utils.despine(left=True)
//  [python]
sns.set_style("white")
plt.figure(figsize=(12, 12))
legend_handles = rnn_cell.draw_graph(
    layout="spiral", neuron_colors={"command": "tab:cyan"}
)
plt.legend(handles=legend_handles, loc="upper center", bbox_to_anchor=(1, 1))
sns.despine(left=True, bottom=True)
//  [python]
sns.set_style("white")
plt.figure(figsize=(12, 12))
legend_handles = rnn_cell.draw_graph(
    layout="spiral", neuron_colors={"command": "tab:cyan"}
)
plt.legend(handles=legend_handles, loc="upper center", bbox_to_anchor=(1, 1))
sns.utils.despine(left=True, bottom=True)
//  [python]
def plot_resampling(X, y, sampler, ax, title=None):
    X_res, y_res = sampler.fit_resample(X, y)
    ax.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.8, edgecolor="k")
    if title is None:
        title = f"Resampling with {sampler.__class__.__name__}"
    ax.set_title(title)
    sns.despine(ax=ax, offset=10)
//  [python]
def plot_resampling(X, y, sampler, ax, title=None):
    X_res, y_res = sampler.fit_resample(X, y)
    ax.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.8, edgecolor="k")
    if title is None:
        title = f"Resampling with {sampler.__class__.__name__}"
    ax.set_title(title)
    sns.utils.despine(ax=ax, offset=10)
//  [python]
def make_histograms(df, ax):
    # Width figure
    kde0 = sns.kdeplot(df[df["estimator"] != "imputed"], ax=ax, x="width", hue="estimator", hue_order=["prediction-powered", "classical"], fill=True, clip=(0,None))
    ax.set_ylabel("")
    ax.set_xlabel("width")
    ax.set_yticks([])
    ax.set_yticklabels([])
    kde0.get_legend().remove()
    sns.despine(ax=ax,top=True,right=True,left=True)
//  [python]
def make_histograms(df, ax):
    # Width figure
    kde0 = sns.kdeplot(df[df["estimator"] != "imputed"], ax=ax, x="width", hue="estimator", hue_order=["prediction-powered", "classical"], fill=True, clip=(0,None))
    ax.set_ylabel("")
    ax.set_xlabel("width")
    ax.set_yticks([])
    ax.set_yticklabels([])
    kde0.get_legend().remove()
    sns.utils.despine(ax=ax,top=True,right=True,left=True)
//  [python]
results['Method'] = methods

plt.figure(figsize=[8,4])
sns.barplot(data=results, x='AUC', y='Method')
plt.xlim(0.2, 0.85)
sns.despine()