jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_discovered_missed_clusters(dataframe, file_path=''):
  """Plot location clusters comparing agents missed and discovered incidents."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.catplot(
      x='param_value',
      y='missed_incidents',
      data=dataframe,
      hue='agent_type',
      palette='deep',
      height=plot_height,
      aspect=aspect_ratio,
      s=8,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Missed incidents for each location', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.tight_layout()
  plt.savefig(file_path + '_missed.pdf')

  sns.catplot(
      x='param_value',
      y='discovered_incidents',
      data=dataframe,
      hue='agent_type',
      height=plot_height,
      aspect=aspect_ratio,
      s=8,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered incidents for each location', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.tight_layout()
  plt.savefig(file_path + '_discovered.pdf')
//  [python]
def plot_optima(
    optima_df: pd.DataFrame,
    categorical_input_cols: Optional[List[str]] = None,
    ncols: int = 3,
    height: float = 3.5,
    aspect: float = 1.2,
    fname: Optional[Path] = None,
) -> sns.FacetGrid:  # pragma: no cover
    """
    Plots for optimal values of input variables, separate the optima based on categorical variable context
    - optima_df is a pandas dataframe with rows being the optima found for each categorical context (opt: for each fold)
    - config is a OptimizerConfig
    """
    assert len(optima_df) > 0
    categorical_input_cols = categorical_input_cols if categorical_input_cols is not None else []
    id_vars = [FOLD] + categorical_input_cols
    feature = "Feature"
    optimal_value = "Optimal value"
    melted = optima_df.melt(id_vars=id_vars, var_name=feature, value_name=optimal_value)
    n_cat_inputs = len(categorical_input_cols)
    hue = categorical_input_cols[1] if n_cat_inputs > 1 else None
    # If any categorical inputs given, vary categ. var. along x-axis. Otherwise vary fold.
    x = FOLD if n_cat_inputs == 0 else categorical_input_cols[0]
    g = sns.factorplot(
        x=x,
        y=optimal_value,
        hue=hue,
        col=feature,
        col_wrap=ncols,
        sharey=False,
        data=melted,
        size=height,
        aspect=aspect,
    )
    if fname is not None:  # pragma: no cover
        g.savefig(fname, bbox_inches="tight")
        # noinspection PyArgumentList
        plt.close()
    return g
//  [python]
def plot_optima(
    optima_df: pd.DataFrame,
    categorical_input_cols: Optional[List[str]] = None,
    ncols: int = 3,
    height: float = 3.5,
    aspect: float = 1.2,
    fname: Optional[Path] = None,
) -> sns.FacetGrid:  # pragma: no cover
    """
    Plots for optimal values of input variables, separate the optima based on categorical variable context
    - optima_df is a pandas dataframe with rows being the optima found for each categorical context (opt: for each fold)
    - config is a OptimizerConfig
    """
    assert len(optima_df) > 0
    categorical_input_cols = categorical_input_cols if categorical_input_cols is not None else []
    id_vars = [FOLD] + categorical_input_cols
    feature = "Feature"
    optimal_value = "Optimal value"
    melted = optima_df.melt(id_vars=id_vars, var_name=feature, value_name=optimal_value)
    n_cat_inputs = len(categorical_input_cols)
    hue = categorical_input_cols[1] if n_cat_inputs > 1 else None
    # If any categorical inputs given, vary categ. var. along x-axis. Otherwise vary fold.
    x = FOLD if n_cat_inputs == 0 else categorical_input_cols[0]
    g = sns.catplot(
        x=x,
        y=optimal_value,
        hue=hue,
        col=feature,
        col_wrap=ncols,
        sharey=False,
        data=melted,
        height=height,
        aspect=aspect,
    )
    if fname is not None:  # pragma: no cover
        g.savefig(fname, bbox_inches="tight")
        # noinspection PyArgumentList
        plt.close()
    return g
//  [python]
def nature_catplot(**kwargs):
    """
    """
    return sns.factorplot(
        # standard error
        errorbar=('ci', 68),
        # legend inside
        legend_out=False,
        # titles of row and col on margins
        margin_titles=True,
        **kwargs,
    )
//  [python]
def nature_catplot(**kwargs):
    """
    """
    return sns.catplot(
        # standard error
        errorbar=('ci', 68),
        # legend inside
        legend_out=False,
        # titles of row and col on margins
        margin_titles=True,
        **kwargs,
    )
//  [python]
def my_catplot(*args, **kwargs):
    """See https://github.com/YuhangSong/general-energy-nets/tree/master/experiments#my_catplot
    """
    return sns.factorplot(*args, **kwargs, errorbar=('ci', 68), kind='point', capsize=0.4, legend_out=False)
//  [python]
def my_catplot(*args, **kwargs):
    """See https://github.com/YuhangSong/general-energy-nets/tree/master/experiments#my_catplot
    """
    return sns.catplot(*args, **kwargs, errorbar=('ci', 68), kind='point', capsize=0.4, legend_out=False)
//  [python]
def bar_plot():
    method_name = "gpt4v_visual_revision_prompting"

    ## load the test scores of GPT-4V 
    with open("../metrics/prediction_file_name_list_part1_new.json", "r") as f:
        file_name_list = json.load(f)
    with open("../metrics/res_dict_part1_new.json", "r") as f:
        res_dict = json.load(f)
    res_lst = res_dict[method_name]

    x_variables = []
    for filename in file_name_list:
        with open("../../testset_final/" + filename, "r") as f:
            html_content = f.read() 
            variable = count_total_nodes(html_content)
            if variable < 141:
                variable = 1 
            elif variable < 270:
                variable = 2
            elif variable < 399:
                variable = 3
            elif variable <= 528:
                variable = 4
            x_variables.append(variable)
    
    y_variables = []
    for i, res in enumerate(res_lst):
        y_variables.append({"performance": res[1], "tags": x_variables[i], "metric": "block"})
        # y_variables.append({"performance": res[2], "tags": x_variables[i], "metric": "text"})
        y_variables.append({"performance": res[3], "tags": x_variables[i], "metric": "position"})
        # y_variables.append({"performance": res[4], "tags": x_variables[i], "metric": "color"})
        y_variables.append({"performance": res[5], "tags": x_variables[i], "metric": "CLIP"})

    # Convert to DataFrame
    df = pd.DataFrame(y_variables)

    # Plotting
    g = sns.factorplot(
        data=df, kind="bar",
        x="tags", y="performance", hue="metric",
        ci="sd", palette="dark", alpha=.6, size=6,
        aspect=2
    )
    g.despine(left=True)
    g.set_axis_labels("Tags", "Performance")
    g.legend.set_title("Metrics")
    plt.show()
//  [python]
def bar_plot():
    method_name = "gpt4v_visual_revision_prompting"

    ## load the test scores of GPT-4V 
    with open("../metrics/prediction_file_name_list_part1_new.json", "r") as f:
        file_name_list = json.load(f)
    with open("../metrics/res_dict_part1_new.json", "r") as f:
        res_dict = json.load(f)
    res_lst = res_dict[method_name]

    x_variables = []
    for filename in file_name_list:
        with open("../../testset_final/" + filename, "r") as f:
            html_content = f.read() 
            variable = count_total_nodes(html_content)
            if variable < 141:
                variable = 1 
            elif variable < 270:
                variable = 2
            elif variable < 399:
                variable = 3
            elif variable <= 528:
                variable = 4
            x_variables.append(variable)
    
    y_variables = []
    for i, res in enumerate(res_lst):
        y_variables.append({"performance": res[1], "tags": x_variables[i], "metric": "block"})
        # y_variables.append({"performance": res[2], "tags": x_variables[i], "metric": "text"})
        y_variables.append({"performance": res[3], "tags": x_variables[i], "metric": "position"})
        # y_variables.append({"performance": res[4], "tags": x_variables[i], "metric": "color"})
        y_variables.append({"performance": res[5], "tags": x_variables[i], "metric": "CLIP"})

    # Convert to DataFrame
    df = pd.DataFrame(y_variables)

    # Plotting
    g = sns.catplot(
        data=df, kind="bar",
        x="tags", y="performance", hue="metric",
        ci="sd", palette="dark", alpha=.6, height=6,
        aspect=2
    )
    g.despine(left=True)
    g.set_axis_labels("Tags", "Performance")
    g.legend.set_title("Metrics")
    plt.show()
//  [python]
def nature_catplot_sharey(*args, **kwargs):
    """
    """
    return sns.factorplot(
        *args, **kwargs,
        # standard error
        errorbar=('ci', 68),
        # bar
        kind='bar',
        # legend inside
        legend_out=False,
        # titles of row and col on margins
        margin_titles=True,
        # sharing y
        sharey=True,
        # # bars for error
        # err_style='bars',
        # err_kws={
        #     # settings for error bars
        #     'capsize': 6,
        #     'capthick': 2,
        # },
    )
//  [python]
def nature_catplot_sharey(*args, **kwargs):
    """
    """
    return sns.catplot(
        *args, **kwargs,
        # standard error
        errorbar=('ci', 68),
        # bar
        kind='bar',
        # legend inside
        legend_out=False,
        # titles of row and col on margins
        margin_titles=True,
        # sharing y
        sharey=True,
        # # bars for error
        # err_style='bars',
        # err_kws={
        #     # settings for error bars
        #     'capsize': 6,
        #     'capthick': 2,
        # },
    )
//  [python]
def generate_precision_plots(prec_df, plot_outdir):

    sns.pointplot(x="k", y="Precision@k", hue="model", hue_order=['AnchoredSiameseGNN'], #, 'SiameseGNN'],
                capsize=.2, palette="YlGnBu_d", data=prec_df)

    make_dirs(plot_outdir)
    plt.savefig(os.path.join(plot_outdir, "precision.eps"))
    plt.close()
//  [python]
def generate_precision_plots(prec_df, plot_outdir):

    sns.catplot(x="k", y="Precision@k", hue="model", hue_order=['AnchoredSiameseGNN'], #, 'SiameseGNN'],
                capsize=.2, palette="YlGnBu_d", height=6, aspect=.75,
                kind="point", data=prec_df)

    make_dirs(plot_outdir)
    plt.savefig(os.path.join(plot_outdir, "precision.eps"))
    plt.close()
//  [python]
def generate_3_metrics_plots(metrics_df, x_label, plot_outdir):

    sns.pointplot(x=x_label, y="Value", hue="model", hue_order=['AnchoredSiameseGNN'], #, 'SiameseGNN'],
                col="Metric", capsize=.2, palette="YlGnBu_d", data=metrics_df)

    make_dirs(plot_outdir)
    plt.savefig(os.path.join(plot_outdir, "3_metrics_plot.eps"))
    plt.close()
//  [python]
def generate_3_metrics_plots(metrics_df, x_label, plot_outdir):

    sns.catplot(x=x_label, y="Value", hue="model", hue_order=['AnchoredSiameseGNN'], #, 'SiameseGNN'],
                col="Metric", capsize=.2, palette="YlGnBu_d", height=6, aspect=.75,
                kind="point", data=metrics_df)

    make_dirs(plot_outdir)
    plt.savefig(os.path.join(plot_outdir, "3_metrics_plot.eps"))
    plt.close()
//  [python]
plt.rcParams["legend.loc"] ='lower center'	 
sns.set_theme(style="darkgrid")
sns.set_context("paper", rc={"lines.linewidth": 0.8, "legend.loc": 'best'})

g = sns.factorplot(x="n", y="Loss", hue="Method", col="Eval",palette="YlGnBu_d", size=2, aspect=1,kind="point", data=df,
legend=True,legend_out=True,
sharex=False,col_wrap=2)
//  [python]
plt.rcParams["legend.loc"] ='lower center'	 
sns.set_theme(style="darkgrid")
sns.set_context("paper", rc={"lines.linewidth": 0.8, "legend.loc": 'best'})

g = sns.catplot(x="n", y="Loss", hue="Method", col="Eval",palette="YlGnBu_d", height=2, aspect=1,kind="point", data=df,
legend=True,legend_out=True,
sharex=False,col_wrap=2)
//  [python]
def gen_plots(data, options):

    # linear plots
    lin_dir = os.path.join(options['out_dir'], 'aug_robust_no_supervised')
    os.makedirs(lin_dir, exist_ok=True)
    linear_data = data[data.result_type=='linear-eval']
    linear_data = linear_data[linear_data.variant=="linear-eval-lr"]
    mpl.style.use('default')
    #since catplot is a figure level function, it produces a new, separate plot which doesn't follow style of past graphs
#     with sns.axes_style("white"):
    fig= sns.factorplot(x='aug_type', y='result', hue='basetrain', data=linear_data, kind="point",s=10,
        linestyles="-", legend_out=False,order=["Baseline","Remove\ngrayscale","Remove\ncolor","Crop + blur\nonly","Crop\nonly"])
        
    #sets axis labels and title of graph
    fig.set(xlabel='Augmentation Sets', ylabel='Change of Accuracy from Baseline', title=options['data_name'].replace("_", " ").title())
    # fig._legend.set_title("Basetrain")
    fig.ax.legend(title="Basetrain", fontsize="large", title_fontsize='large')
    for ax in fig.axes.flat:
        ax.set_title(options['data_name'].replace("_", " ").title(), fontsize=20)
        ax.set_xlabel("Augmentation Sets", fontsize=18)

        if 'chexpert' in options['data_name']:
            ax.set_ylabel("AUROC Change", fontsize=18)
        else:
            ax.set_ylabel("Accuracy Change", fontsize=18)
        xticks = ["Baseline","Remove\ngrayscale","Remove\ncolor","Crop+Blur\nonly","Crop\nonly"]
        ax.set_xticklabels(xticks, rotation=0, fontsize=12)
        
        yticks = [item.get_text() for item in ax.get_yticklabels()]
        ax.set_yticklabels(yticks, rotation=0, fontsize=17)
        # ax.tick_params(axis='y', labelsize='large')

        ax.spines['bottom'].set_color('1')
        ax.spines['top'].set_color('1')
        ax.spines['right'].set_color('1')
        ax.spines['left'].set_color('1')
        ax.patch.set_facecolor('0.97')
        ax.grid(axis='y', color='grey', dashes=[10, 4])

#         print(ax.spines)

#         ax.legend(fontsize=8)
    #gets rid of other graph created 
    plt.close(1)

    #creates output file
    outplot = os.path.join(lin_dir, '{}_{}.pdf'.format(options['data_name']+ "_augmentation", "no_supervised"))

    #saves Figure 1, but Figure 1 is the empty graph created (NOT SNS Graph)
    fig.savefig(outplot, format='pdf', bbox_inches='tight')
//  [python]
def gen_plots(data, options):

    # linear plots
    lin_dir = os.path.join(options['out_dir'], 'aug_robust_no_supervised')
    os.makedirs(lin_dir, exist_ok=True)
    linear_data = data[data.result_type=='linear-eval']
    linear_data = linear_data[linear_data.variant=="linear-eval-lr"]
    mpl.style.use('default')
    #since catplot is a figure level function, it produces a new, separate plot which doesn't follow style of past graphs
#     with sns.axes_style("white"):
    fig= sns.catplot(x='aug_type', y='result', hue='basetrain', data=linear_data, kind="point",s=10,
        linestyle="-", legend_out=False,order=["Baseline","Remove\ngrayscale","Remove\ncolor","Crop + blur\nonly","Crop\nonly"])
        
    #sets axis labels and title of graph
    fig.set(xlabel='Augmentation Sets', ylabel='Change of Accuracy from Baseline', title=options['data_name'].replace("_", " ").title())
    # fig._legend.set_title("Basetrain")
    fig.ax.legend(title="Basetrain", fontsize="large", title_fontsize='large')
    for ax in fig.axes.flat:
        ax.set_title(options['data_name'].replace("_", " ").title(), fontsize=20)
        ax.set_xlabel("Augmentation Sets", fontsize=18)

        if 'chexpert' in options['data_name']:
            ax.set_ylabel("AUROC Change", fontsize=18)
        else:
            ax.set_ylabel("Accuracy Change", fontsize=18)
        xticks = ["Baseline","Remove\ngrayscale","Remove\ncolor","Crop+Blur\nonly","Crop\nonly"]
        ax.set_xticklabels(xticks, rotation=0, fontsize=12)
        
        yticks = [item.get_text() for item in ax.get_yticklabels()]
        ax.set_yticklabels(yticks, rotation=0, fontsize=17)
        # ax.tick_params(axis='y', labelsize='large')

        ax.spines['bottom'].set_color('1')
        ax.spines['top'].set_color('1')
        ax.spines['right'].set_color('1')
        ax.spines['left'].set_color('1')
        ax.patch.set_facecolor('0.97')
        ax.grid(axis='y', color='grey', dashes=[10, 4])

#         print(ax.spines)

#         ax.legend(fontsize=8)
    #gets rid of other graph created 
    plt.close(1)

    #creates output file
    outplot = os.path.join(lin_dir, '{}_{}.pdf'.format(options['data_name']+ "_augmentation", "no_supervised"))

    #saves Figure 1, but Figure 1 is the empty graph created (NOT SNS Graph)
    fig.savefig(outplot, format='pdf', bbox_inches='tight')
//  [python]
sns.set(style="darkgrid")

iris = sns.load_dataset("iris")
sns.boxplot(data=iris, orient="h")
//  [python]
sns.set(style="darkgrid")

iris = sns.load_dataset("iris")
sns.catplot(data=iris, orient="h", kind="box")
//  [python]
def make_catplot(x, y, data, ylabel, **plotopts):
    g = sns.factorplot(x=x, y=y, data=data, **plotopts)
    g.set_titles(col_template = "{col_name}")
    g.set(xlabel=None)
    g.set_ylabels(ylabel, clear_inner=False);
    g.set_xticklabels(rotation=45, fontsize=16, ha='right', rotation_mode='anchor')
    g._legend.set_title('ContributionID')
    # Add vertical add midpoints between each major tick
    for ax in g.axes.flatten():
        ax.xaxis.set_minor_locator(AutoMinorLocator(2))
        ax.grid(which="minor", axis='x', linestyle=":")
        # Hide the minor ticks (distracting) by making it white
        ax.tick_params(axis='x', which='minor', colors='white')
    plt.show()
//  [python]
def make_catplot(x, y, data, ylabel, **plotopts):
    g = sns.catplot(x=x, y=y, data=data, **plotopts)
    g.set_titles(col_template = "{col_name}")
    g.set(xlabel=None)
    g.set_ylabels(ylabel, clear_inner=False);
    g.set_xticklabels(rotation=45, fontsize=16, ha='right', rotation_mode='anchor')
    g._legend.set_title('ContributionID')
    # Add vertical add midpoints between each major tick
    for ax in g.axes.flatten():
        ax.xaxis.set_minor_locator(AutoMinorLocator(2))
        ax.grid(which="minor", axis='x', linestyle=":")
        # Hide the minor ticks (distracting) by making it white
        ax.tick_params(axis='x', which='minor', colors='white')
    plt.show()
//  [python]
def plot_seaborn_fmri():
    sns.factorplot(x="timepoint", y="signal", hue="subject",
                col="event", row="region", data=fmri, kind="point", alpha=.5)
    plt.show()
//  [python]
def plot_seaborn_fmri():
    sns.catplot(x="timepoint", y="signal", hue="subject",
                col="event", row="region", data=fmri, kind="point", alpha=.5)
    plt.show()
//  [python]
def catplot(data, *args, **kwargs):
    return sns.factorplot(data, *args, **kwargs)
//  [python]
def catplot(data, *args, **kwargs):
    return sns.catplot(data, *args, **kwargs)
//  [python]
fig_output_dir = Path("./figures")
cm2in = 0.39

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
        description="Creates figure for runtime of fast bss eval vs ci-sdr"
    )
    parser.add_argument("datafile", type=Path, help="Path to data file")
    args = parser.parse_args()

    os.makedirs(fig_output_dir, exist_ok=True)

    with open(args.datafile, "r") as f:
        data = json.load(f)

    df = pd.DataFrame(data)

    df = df.rename(
        columns={
            "signal_length": "Signal length",
            "filter_length": "Filter length",
            "runtime": "Runtime (s)",
            "channels": "Channels",
            "algo": "Package",
        }
    )

    df = df.replace(
        {
            "cisdr": "CI-SDR",
            "solve": "Proposed (solve)",
            "cgd": "Proposed (CGD)",
        }
    )

    sns.set_theme(context="paper", style="whitegrid")

    g = sns.factorplot(
        data=df,
        row="Signal length",
        col="Filter length",
        x="Channels",
        hue="Package",
        y="Runtime (s)",
        kind="bar",
        margin_titles=True,
        legend=True,
        aspect=1.0,
        size=8.5 * cm2in / 2.0,
        log=False,
    )

    g.set_titles(row_template="{row_name:.0f} s", col_template="{col_name} taps")

    # g.fig.tight_layout()

    # g.fig.legend(fontsize="x-small")

    plt.savefig(fig_output_dir / "runtime_vs_cisdr.pdf")

    # Create the latex table
    table_ms = df.rename(columns={"Runtime (s)": "Runtime (ms)"}).pivot_table(
        values=["Runtime (ms)", "speedup"],
        index=["Channels", "Package"],
        columns=["Signal length", "Filter length"],
    )
    table_ms["Runtime (ms)"] = table_ms["Runtime (ms)"].apply(lambda x: x * 1000)
    table_ms["speedup"] = table_ms["speedup"].applymap(lambda x: f"(${x:.0f}\times$)")

    table_ms = table_ms.reorder_levels([2, 1, 0], axis="columns").sort_index(
        axis="columns"
    )

    print(table_ms.to_latex(float_format="%.0f", escape=False))
    print()
    print(table_ms)
//  [python]
fig_output_dir = Path("./figures")
cm2in = 0.39

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
        description="Creates figure for runtime of fast bss eval vs ci-sdr"
    )
    parser.add_argument("datafile", type=Path, help="Path to data file")
    args = parser.parse_args()

    os.makedirs(fig_output_dir, exist_ok=True)

    with open(args.datafile, "r") as f:
        data = json.load(f)

    df = pd.DataFrame(data)

    df = df.rename(
        columns={
            "signal_length": "Signal length",
            "filter_length": "Filter length",
            "runtime": "Runtime (s)",
            "channels": "Channels",
            "algo": "Package",
        }
    )

    df = df.replace(
        {
            "cisdr": "CI-SDR",
            "solve": "Proposed (solve)",
            "cgd": "Proposed (CGD)",
        }
    )

    sns.set_theme(context="paper", style="whitegrid")

    g = sns.catplot(
        data=df,
        row="Signal length",
        col="Filter length",
        x="Channels",
        hue="Package",
        y="Runtime (s)",
        kind="bar",
        margin_titles=True,
        legend=True,
        aspect=1.0,
        height=8.5 * cm2in / 2.0,
        log=False,
    )

    g.set_titles(row_template="{row_name:.0f} s", col_template="{col_name} taps")

    # g.fig.tight_layout()

    # g.fig.legend(fontsize="x-small")

    plt.savefig(fig_output_dir / "runtime_vs_cisdr.pdf")

    # Create the latex table
    table_ms = df.rename(columns={"Runtime (s)": "Runtime (ms)"}).pivot_table(
        values=["Runtime (ms)", "speedup"],
        index=["Channels", "Package"],
        columns=["Signal length", "Filter length"],
    )
    table_ms["Runtime (ms)"] = table_ms["Runtime (ms)"].apply(lambda x: x * 1000)
    table_ms["speedup"] = table_ms["speedup"].applymap(lambda x: f"(${x:.0f}\times$)")

    table_ms = table_ms.reorder_levels([2, 1, 0], axis="columns").sort_index(
        axis="columns"
    )

    print(table_ms.to_latex(float_format="%.0f", escape=False))
    print()
    print(table_ms)
//  [python]
def visualize_DP(Xdata, Xlayer = "dp_bin", chr_lst = ["18p", "18q"]):
    """
    """
    data_used = get_count_df(Xdata, Xlayer, chr_lst)

    import seaborn as sns
    import matplotlib.pylab as plt
    ## for all cells(no clear information)
    fig, ax = plt.subplots(figsize=(40, 10))
    ax = sns.boxplot(x="bins_loc", y="count",  data=data_used, palette="Set3", fliersize=1,
                     linewidth=1)
    ax.set_title('Box plot of DP count-all cells and for different cell type')

    ## for each celltype
    g = sns.FacetGrid(data_used, col="cell_type", height=4, aspect=5, col_wrap=1)
    g.map(sns.boxplot, "bins_loc", "count", palette="Set3", fliersize=1, linewidth=1, whis=2)
    plt.show()   

    return None
//  [python]
def visualize_DP(Xdata, Xlayer = "dp_bin", chr_lst = ["18p", "18q"]):
    """
    """
    data_used = get_count_df(Xdata, Xlayer, chr_lst)

    import seaborn as sns
    import matplotlib.pylab as plt
    ## for all cells(no clear information)
    fig, ax = plt.subplots(figsize=(40, 10))
    ax = sns.boxplot(x="bins_loc", y="count",  data=data_used, palette="Set3", fliersize=1,
                     linewidth=1)
    ax.set_title('Box plot of DP count-all cells and for different cell type')

    ## for each celltype
    sns.catplot(x="bins_loc", y="count", data=data_used, palette="Set3", fliersize=1,
                     linewidth=1, col="cell_type", kind="box",whis=2, 
                height=4, aspect=5, orient = "v", col_wrap =1)
    plt.show()   

    return None
//  [python]
def _plot_scores(df, xlabel, aspect=.5):
    g = sns.barplot(x=xlabel, y='label', data=df, hue='vecs', hue_order=['wiki+subs', 'subs', 'wiki'],
                    height=len(df) / 12, aspect=aspect
                    )

    g.set(xticks=(0, .2, .4, .6, .8, 1))
    g.ax.yaxis.tick_right()

    g.despine(left=True, right=False)
    g.set(xlim=(1.1, 0), ylabel=None)
    g.legend(loc='upper left', bbox_to_anchor=(1.1, 0), frameon=False)
    return g
//  [python]
def _plot_scores(df, xlabel, aspect=.5):
    g = sns.catplot(x=xlabel, y='label', kind='bar', data=df, legend=False,
                    hue='vecs', hue_order=['wiki+subs', 'subs', 'wiki'],
                    height=len(df) / 12, aspect=aspect
                    )

    g.set(xticks=(0, .2, .4, .6, .8, 1))
    g.ax.yaxis.tick_right()

    g.despine(left=True, right=False)
    g.set(xlim=(1.1, 0), ylabel=None)
    g.ax.legend(loc='upper left', bbox_to_anchor=(1.1, 0), frameon=False)
    return g
//  [python]
def plot_metrics_at_k(metric_results: Union[Dict[str, Dict[str, float]], List[Dict[str, Dict[str, float]]]], **kwargs):
    """
    Plots recommendation metric values (y-axis) for different values of k (x-axis)
    for each of the benchmark algorithms.

    Parameters
    ----------
    metric_results : Union[Dict[str, Dict[str, float]], List[Dict[str, Dict[str, float]]]]
        Nested-dictionary or list of dictionaries with evaluation results returned by benchmark function.
    **kwargs
        Other parameters passed to ``sns.catplot``.

    Returns
    -------
    ax : matplotlib.axes.Axes
        The plot with metric values.
    """

    if not isinstance(metric_results, list):
        metric_results_list = [metric_results]
    else:
        metric_results_list = metric_results

    # Format data for plot
    out = []
    for metric_results in metric_results_list:
        for algo_name, results in metric_results.items():
            for metric_name, value in results.items():
                d = {'algorithm': algo_name,
                     'metric_name': metric_name.split('@')[0],
                     'k': int(metric_name.split('@')[1]),
                     'value': value}
                out.append(d)
    df = pd.DataFrame(out)

    # Plot
    ax = sns.factorplot(x='k', y='value', col='metric_name', hue='algorithm', data=df, kind='point',
                     sharey=False, **kwargs)
    return ax
//  [python]
def plot_metrics_at_k(metric_results: Union[Dict[str, Dict[str, float]], List[Dict[str, Dict[str, float]]]], **kwargs):
    """
    Plots recommendation metric values (y-axis) for different values of k (x-axis)
    for each of the benchmark algorithms.

    Parameters
    ----------
    metric_results : Union[Dict[str, Dict[str, float]], List[Dict[str, Dict[str, float]]]]
        Nested-dictionary or list of dictionaries with evaluation results returned by benchmark function.
    **kwargs
        Other parameters passed to ``sns.catplot``.

    Returns
    -------
    ax : matplotlib.axes.Axes
        The plot with metric values.
    """

    if not isinstance(metric_results, list):
        metric_results_list = [metric_results]
    else:
        metric_results_list = metric_results

    # Format data for plot
    out = []
    for metric_results in metric_results_list:
        for algo_name, results in metric_results.items():
            for metric_name, value in results.items():
                d = {'algorithm': algo_name,
                     'metric_name': metric_name.split('@')[0],
                     'k': int(metric_name.split('@')[1]),
                     'value': value}
                out.append(d)
    df = pd.DataFrame(out)

    # Plot
    ax = sns.catplot(x='k', y='value', col='metric_name', hue='algorithm', data=df, kind='point',
                     sharey=False, **kwargs)
    return ax
//  [python]
def visualize_emm_prob(Xdata, 
                       uns_key = "posterior_mtx",
                       chr_lst = ["1q"], 
                       CNV_state_order = ["copy loss(0.01)", "copy loss(0.99)", "copy neutral", "copy gain(1/3)", "copy gain(2/3)"]):
    """
    """
    print("[XClone]visualization emm_prob of chr: ", chr_lst )
    bin_flag = Xdata.var["chr_arm"].isin(chr_lst)
    
    prob_used = Xdata.uns[uns_key][:, bin_flag,:].copy()
    Xdata_used = Xdata[:, bin_flag].copy()
    
    transferrred_df = transfer_prob_to_df(prob_used, Xdata_used, CNV_state_order = CNV_state_order)
    
    
    data_used = transferrred_df.copy()
    obs_df = Xdata_used.obs.copy()
    data_used1 = pd.merge(data_used, obs_df["cell_type"], left_on = "cell_barcodes", right_index = True)
    
    import seaborn as sns
    import matplotlib.pylab as plt
    # %matplotlib inline
    
    ## for all cells(no clear information)
    fig, ax = plt.subplots(figsize=(40, 10))
    ax = sns.boxplot(x="bins_loc", y="prob", hue="CNV_states", data=data_used1, palette="Set3", fliersize=1,
                     linewidth=1)
    ax.set_title('Box plot of beta binomial prob for different CNV states')
    
    ## for each celltype
    g = sns.FacetGrid(data_used1, col="cell_type", height=4, aspect=5)
    g.map(sns.boxplot, "bins_loc", "prob", "CNV_states", palette="Set3", fliersize=1, linewidth=1)
    g.add_legend()
    plt.show()
    return None
//  [python]
def visualize_emm_prob(Xdata, 
                       uns_key = "posterior_mtx",
                       chr_lst = ["1q"], 
                       CNV_state_order = ["copy loss(0.01)", "copy loss(0.99)", "copy neutral", "copy gain(1/3)", "copy gain(2/3)"]):
    """
    """
    print("[XClone]visualization emm_prob of chr: ", chr_lst )
    bin_flag = Xdata.var["chr_arm"].isin(chr_lst)
    
    prob_used = Xdata.uns[uns_key][:, bin_flag,:].copy()
    Xdata_used = Xdata[:, bin_flag].copy()
    
    transferrred_df = transfer_prob_to_df(prob_used, Xdata_used, CNV_state_order = CNV_state_order)
    
    
    data_used = transferrred_df.copy()
    obs_df = Xdata_used.obs.copy()
    data_used1 = pd.merge(data_used, obs_df["cell_type"], left_on = "cell_barcodes", right_index = True)
    
    import seaborn as sns
    import matplotlib.pylab as plt
    # %matplotlib inline
    
    ## for all cells(no clear information)
    fig, ax = plt.subplots(figsize=(40, 10))
    ax = sns.boxplot(x="bins_loc", y="prob", hue="CNV_states", data=data_used1, palette="Set3", fliersize=1,
                     linewidth=1)
    ax.set_title('Box plot of beta binomial prob for different CNV states')
    
    ## for each celltype
    sns.catplot(x="bins_loc", y="prob", hue="CNV_states", data=data_used1, palette="Set3", fliersize=1,
                     linewidth=1, col="cell_type", kind="box",
                height=4, aspect=5, orient = "v", col_wrap =1)
    plt.show()
    return None
//  [python]
data=[]
with open(sys.argv[1]) as f:
	for row in f:
		l=row.replace(">>","").split()
		x = []
		for i in range(0,len(l)-5):
			x.append(float(l[i]))
		xx = x.copy()
		xx.append(float(l[-5]))
		xx.append(10)
		data.append(xx)
		xx = x.copy()
		xx.append(float(l[-4]))
		xx.append(30)
		data.append(xx)
		xx = x.copy()
		xx.append(float(l[-3]))
		xx.append(50)
		data.append(xx)
		xx = x.copy()
		xx.append(float(l[-2]))
		xx.append(70)
		data.append(xx)
		xx = x.copy()
		xx.append(float(l[-1]))
		xx.append(90)
		data.append(xx)
		
d = pd.DataFrame(data,columns=["charge","eval-set","max_depth","num_leaves","value","percentile"])
		
with PdfPages('%s.pdf'%sys.argv[1]) as pdf:
	sns.factorplot(x="percentile",y="value",hue="charge",col="eval-set",data=d,kind="point",ci="sd")
	pdf.savefig()
	plt.close() 
	sns.factorplot(x="percentile",y="value",hue="max_depth",col="eval-set",data=d,kind="point",ci="sd")
	pdf.savefig()
	plt.close() 
	sns.factorplot(x="percentile",y="value",hue="num_leaves",col="eval-set",data=d,kind="point",ci="sd")
	pdf.savefig()
	plt.close()
//  [python]
data=[]
with open(sys.argv[1]) as f:
	for row in f:
		l=row.replace(">>","").split()
		x = []
		for i in range(0,len(l)-5):
			x.append(float(l[i]))
		xx = x.copy()
		xx.append(float(l[-5]))
		xx.append(10)
		data.append(xx)
		xx = x.copy()
		xx.append(float(l[-4]))
		xx.append(30)
		data.append(xx)
		xx = x.copy()
		xx.append(float(l[-3]))
		xx.append(50)
		data.append(xx)
		xx = x.copy()
		xx.append(float(l[-2]))
		xx.append(70)
		data.append(xx)
		xx = x.copy()
		xx.append(float(l[-1]))
		xx.append(90)
		data.append(xx)
		
d = pd.DataFrame(data,columns=["charge","eval-set","max_depth","num_leaves","value","percentile"])
		
with PdfPages('%s.pdf'%sys.argv[1]) as pdf:
	sns.catplot(x="percentile",y="value",hue="charge",col="eval-set",data=d,kind="point",ci="sd")
	pdf.savefig()
	plt.close() 
	sns.catplot(x="percentile",y="value",hue="max_depth",col="eval-set",data=d,kind="point",ci="sd")
	pdf.savefig()
	plt.close() 
	sns.catplot(x="percentile",y="value",hue="num_leaves",col="eval-set",data=d,kind="point",ci="sd")
	pdf.savefig()
	plt.close()
//  [python]
def gen_disentaglement_adversarial_comparison(df_image):
    print(f"Generating disentaglement adversarial plot with ood=False")
    df = df_image[df_image["OOD"]==False]
    
    uncertainty_df = df[['Epsilon','aleatoric','epistemic']]
    melt_uncertainty_df = pd.melt(uncertainty_df, id_vars=['Epsilon'], var_name=['uncertain'])
    print (melt_uncertainty_df.head())
    melt_uncertainty_df['Mean'] = [np.array(x).mean() for x in melt_uncertainty_df.value.values]
    print (melt_uncertainty_df.head())
    
    sns.boxplot(x='Epsilon', y='Mean', hue='uncertain', data=melt_uncertainty_df)
    plt.savefig(os.path.join(output_dir, f"combined_adversairal_disentaglement_box.pdf"))
    plt.show()
//  [python]
def gen_disentaglement_adversarial_comparison(df_image):
    print(f"Generating disentaglement adversarial plot with ood=False")
    df = df_image[df_image["OOD"]==False]
    
    uncertainty_df = df[['Epsilon','aleatoric','epistemic']]
    melt_uncertainty_df = pd.melt(uncertainty_df, id_vars=['Epsilon'], var_name=['uncertain'])
    print (melt_uncertainty_df.head())
    melt_uncertainty_df['Mean'] = [np.array(x).mean() for x in melt_uncertainty_df.value.values]
    print (melt_uncertainty_df.head())
    
    sns.catplot(x='Epsilon', y='Mean', hue='uncertain', data=melt_uncertainty_df, kind="box")
    plt.savefig(os.path.join(output_dir, f"combined_adversairal_disentaglement_box.pdf"))
    plt.show()
//  [python]
def SavePlot(args, path, x = None, y = None, row = None, col = None, hue = None, data = None, kind = None, legend = False, rotation = 45, font_scale = 1.5, xticks = None, ylim = None, Title = True):
    sns.set_style("whitegrid")

    font = 32

    sns.set(rc={'figure.figsize':(17.7,8.27)})

    s1 = sns.factorplot(data = data, x = x, y = y, hue = hue, kind = kind, col = col, row = row, errorbar = 'sd', size = 6, aspect = 2, legend = legend, legend_out = False, palette = ['orange', 'magenta', 'blue', 'lime'])
    axes = s1.axes.flatten()
    if not Title:
        s1.set(title = '')

    if y == 'Marginal Coverage':
        for i, ax in enumerate(axes):
            s1.set_xticklabels(xticks, fontsize = font, rotation = rotation)

            ax.tick_params(axis = 'y', labelsize = font)

            ax.set_title(label = ax.get_title(), fontsize = font)
            ax.axhline(1-args.alpha, ls='--', c='red', linewidth = 6)
            RedLine = mlines.Line2D([], [], color='red', linestyle='--',
                            markersize=font, label='Target Coverage', linewidth = 6)


            if i == 0:
                ax.legend(handles=[RedLine], loc='upper right', frameon=True, fontsize=30, fancybox=True, framealpha=0.9, ncols = 1)
            ax.set_xticklabels(xticks, fontsize = font, rotation = rotation)
            ax.tick_params(labelbottom=True)

        s1.set_axis_labels('', "Marginal Coverage", fontsize = font)


        s1.set(ylim=(0.80, 1.0))

    if y == 'Prediction Size':
        for i, ax in enumerate(axes):
            s1.set_xticklabels(xticks, fontsize = font, rotation = rotation)
            ax.set_title(label = ax.get_title(), fontsize = font)
            ax.tick_params(axis = 'y', labelsize = font)
                                                   

            ax.set_xticklabels(xticks, fontsize = font, rotation = rotation)
            ax.tick_params(labelbottom=True)

        s1.set_axis_labels('', "Prediction Set Size", fontsize = font)

        s1.set(ylim=ylim)


    s1.set_xticklabels(xticks, fontsize = font, rotation = rotation)


    plt.tight_layout()
    s1.savefig(path, dpi = 100, bbox_inches='tight', pad_inches=.1)
    plt.close('all')
//  [python]
def SavePlot(args, path, x = None, y = None, row = None, col = None, hue = None, data = None, kind = None, legend = False, rotation = 45, font_scale = 1.5, xticks = None, ylim = None, Title = True):
    sns.set_style("whitegrid")

    font = 32

    sns.set(rc={'figure.figsize':(17.7,8.27)})

    s1 = sns.catplot(data = data, x = x, y = y, hue = hue, kind = kind, col = col, row = row, errorbar = 'sd', height = 6, aspect = 2, legend = legend, legend_out = False, palette = ['orange', 'magenta', 'blue', 'lime'])
    axes = s1.axes.flatten()
    if not Title:
        s1.set(title = '')

    if y == 'Marginal Coverage':
        for i, ax in enumerate(axes):
            s1.set_xticklabels(xticks, fontsize = font, rotation = rotation)

            ax.tick_params(axis = 'y', labelsize = font)

            ax.set_title(label = ax.get_title(), fontsize = font)
            ax.axhline(1-args.alpha, ls='--', c='red', linewidth = 6)
            RedLine = mlines.Line2D([], [], color='red', linestyle='--',
                            markersize=font, label='Target Coverage', linewidth = 6)


            if i == 0:
                ax.legend(handles=[RedLine], loc='upper right', frameon=True, fontsize=30, fancybox=True, framealpha=0.9, ncols = 1)
            ax.set_xticklabels(xticks, fontsize = font, rotation = rotation)
            ax.tick_params(labelbottom=True)

        s1.set_axis_labels('', "Marginal Coverage", fontsize = font)


        s1.set(ylim=(0.80, 1.0))

    if y == 'Prediction Size':
        for i, ax in enumerate(axes):
            s1.set_xticklabels(xticks, fontsize = font, rotation = rotation)
            ax.set_title(label = ax.get_title(), fontsize = font)
            ax.tick_params(axis = 'y', labelsize = font)
                                                   

            ax.set_xticklabels(xticks, fontsize = font, rotation = rotation)
            ax.tick_params(labelbottom=True)

        s1.set_axis_labels('', "Prediction Set Size", fontsize = font)

        s1.set(ylim=ylim)


    s1.set_xticklabels(xticks, fontsize = font, rotation = rotation)


    plt.tight_layout()
    s1.savefig(path, dpi = 100, bbox_inches='tight', pad_inches=.1)
    plt.close('all')
//  [python]
del df['location']

# checking null values
df.isnull().sum()

# Number of cities we have
len(df['city'].value_counts())

# plotting number of restaurtants that take online_order
sns.set_context("paper", font_scale = 2, rc = {"font.size": 20,"axes.titlesize": 25,"axes.labelsize": 20})   
sns.countplot(data = df, x = 'online_order')
//  [python]
del df['location']

# checking null values
df.isnull().sum()

# Number of cities we have
len(df['city'].value_counts())

# plotting number of restaurtants that take online_order
sns.set_context("paper", font_scale = 2, rc = {"font.size": 20,"axes.titlesize": 25,"axes.labelsize": 20})   
sns.catplot(data = df, kind = 'count', x = 'online_order')
//  [python]
def gen_disentaglement_comparison(df_image):
    
    df = df_image[df_image["Epsilon"]==0.0] # Remove adversarial noise experiments
    df_pixel = df_image_to_pixels(df, keys=["Target", "Mu", "Sigma", "OOD", "aleatoric", "epistemic"])
    df_by_image = df_pixel.groupby([df_pixel.index, "Method","Model Path", "OOD"])

    df_mean_unc_img = df_by_image["aleatoric"].mean().reset_index() #mean of all pixels in every method and image
    #sns.boxplot(x="Method", y="aleatoric", hue="OOD", data=df_mean_unc_img, whis=0.5, showfliers=False)
    #plt.savefig(os.path.join(output_dir, f"ood_aleatoric_box.pdf"))

    df_mean_unc_img = df_by_image["epistemic"].mean().reset_index() #mean of all pixels in every method and image
    #sns.boxplot(x="Method", y="epistemic", hue="OOD", data=df_mean_unc_img, whis=0.5, showfliers=False)
    #plt.savefig(os.path.join(output_dir, f"ood_epistemic_box.pdf"))

    
    uncertainty_df = df[['OOD','aleatoric','epistemic']]
    melt_uncertainty_df = pd.melt(uncertainty_df, id_vars=['OOD'], var_name=['uncertain'])
    print (melt_uncertainty_df.head())
    melt_uncertainty_df['Mean'] = [np.array(x).mean() for x in melt_uncertainty_df.value.values]
    print (melt_uncertainty_df.head())
    
    sns.boxplot(x='OOD', y='Mean', hue='uncertain', data=melt_uncertainty_df)
    plt.savefig(os.path.join(output_dir, f"combined_ood_box.pdf"))
    plt.show()
//  [python]
def gen_disentaglement_comparison(df_image):
    
    df = df_image[df_image["Epsilon"]==0.0] # Remove adversarial noise experiments
    df_pixel = df_image_to_pixels(df, keys=["Target", "Mu", "Sigma", "OOD", "aleatoric", "epistemic"])
    df_by_image = df_pixel.groupby([df_pixel.index, "Method","Model Path", "OOD"])

    df_mean_unc_img = df_by_image["aleatoric"].mean().reset_index() #mean of all pixels in every method and image
    #sns.catplot(x="Method", y="aleatoric", hue="OOD", data=df_mean_unc_img, kind="box", whis=0.5, showfliers=False)
    #plt.savefig(os.path.join(output_dir, f"ood_aleatoric_box.pdf"))

    df_mean_unc_img = df_by_image["epistemic"].mean().reset_index() #mean of all pixels in every method and image
    #sns.catplot(x="Method", y="epistemic", hue="OOD", data=df_mean_unc_img, kind="box", whis=0.5, showfliers=False)
    #plt.savefig(os.path.join(output_dir, f"ood_epistemic_box.pdf"))

    
    uncertainty_df = df[['OOD','aleatoric','epistemic']]
    melt_uncertainty_df = pd.melt(uncertainty_df, id_vars=['OOD'], var_name=['uncertain'])
    print (melt_uncertainty_df.head())
    melt_uncertainty_df['Mean'] = [np.array(x).mean() for x in melt_uncertainty_df.value.values]
    print (melt_uncertainty_df.head())
    
    sns.catplot(x='OOD', y='Mean', hue='uncertain', data=melt_uncertainty_df, kind="box")
    plt.savefig(os.path.join(output_dir, f"combined_ood_box.pdf"))
    plt.show()
//  [python]
def plot(self, outname=None):
        bench_df = pd.DataFrame(
            [row[:2] + [row[2][-1]] + row[3:] for row in self.benchmark_results],
            columns=["reference", "network", "tissue", "pr_auc", "roc_auc"],
        )

        for metric in ["pr_auc", "roc_auc"]:
            sns.set_context(
                "paper",
                rc={
                    "font.size": 16,
                    "axes.titlesize": 16,
                    "axes.labelsize": 16,
                    "xtick.labelsize": 16,
                    "ytick.labelsize": 16,
                },
            )
            order = (
                bench_df[bench_df["network"] != "baseline"]
                .groupby("network")
                .mean()[metric]
                .sort_values()
                .index[::-1]
            )

            g = sns.factorplot(
                data=bench_df[bench_df["network"] != "baseline"],
                y="network",
                x=metric,
                col="reference",
                kind="box",
                order=order,
                fliersize=0,
                boxprops={"alpha": 0.5},
                sharex=False,
                aspect=1.3,
            )

            for subplot in g.axes:
                for ax in subplot:
                    for line in ax.lines:
                        line.set_alpha(0.3)

            g.map(
                sns.stripplot,
                metric,
                "network",
                color="black",
                # data=bench_df[bench_df["network"] != "baseline"],
                s=8,
                jitter=0.25,
                alpha=0.7,
                order=order,
            )
            # g.set_xticklabels(rotation=30)

            if outname:
                extension = os.path.splitext(outname)[1]
                g.savefig(outname.replace(extension, f".{metric}{extension}"))
//  [python]
def plot(self, outname=None):
        bench_df = pd.DataFrame(
            [row[:2] + [row[2][-1]] + row[3:] for row in self.benchmark_results],
            columns=["reference", "network", "tissue", "pr_auc", "roc_auc"],
        )

        for metric in ["pr_auc", "roc_auc"]:
            sns.set_context(
                "paper",
                rc={
                    "font.size": 16,
                    "axes.titlesize": 16,
                    "axes.labelsize": 16,
                    "xtick.labelsize": 16,
                    "ytick.labelsize": 16,
                },
            )
            order = (
                bench_df[bench_df["network"] != "baseline"]
                .groupby("network")
                .mean()[metric]
                .sort_values()
                .index[::-1]
            )

            g = sns.catplot(
                data=bench_df[bench_df["network"] != "baseline"],
                y="network",
                x=metric,
                col="reference",
                kind="box",
                order=order,
                fliersize=0,
                boxprops={"alpha": 0.5},
                sharex=False,
                aspect=1.3,
            )

            for subplot in g.axes:
                for ax in subplot:
                    for line in ax.lines:
                        line.set_alpha(0.3)

            g.map(
                sns.stripplot,
                metric,
                "network",
                color="black",
                # data=bench_df[bench_df["network"] != "baseline"],
                s=8,
                jitter=0.25,
                alpha=0.7,
                order=order,
            )
            # g.set_xticklabels(rotation=30)

            if outname:
                extension = os.path.splitext(outname)[1]
                g.savefig(outname.replace(extension, f".{metric}{extension}"))
//  [python]
def publish_distribution_data_seaborn(
        data_frame: pandas.DataFrame,
        variable: str,
        plot_categories: str,
        within_plot_categories: str,
        pdf: PdfPages,
        plot_titles: Optional[list[str]] = None,
        category_titles: Optional[list[str]] = None,
        panel_height: float = 2,
        panel_aspect: float = 1.3,
        row_length: int = 2,
        common_xlabel: Optional[str] = None,
        common_ylabel: Optional[str] = None,
        suptitle: Optional[str] = None,
        ref_line_y: Optional[float] = None,
) -> None:
    # sns.set(font='serif', style=None, rc={
    #         'font.style': 'italic', 'text.usetex': True})
    grid = sns.FacetGrid(
        data=data_frame, col=plot_categories, col_wrap=2,
        height=panel_height, aspect=panel_aspect
    )
    grid.map(sns.violinplot, within_plot_categories, variable, cut=0, inner=None, scale='width')
    grid.map(sns.swarmplot, within_plot_categories, variable, size=2, color='orange')

    if ref_line_y:
        grid.refline(y=ref_line_y, linestyle=':')

    if category_titles:
        grid.set_xticklabels(category_titles, step=1)

    # plot_categories = ["l$\infty$" if metric ==
    #                    "l_inf" else metric for metric in plot_categories]

    pdf.savefig(plt.gcf())