jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def analyze_pcap(rl_algos, tcp_algos, plt_name, runs, data_dir):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import seaborn as sns

    algos = rl_algos + tcp_algos
    host_rtt = {}
    for algo in algos:
        host_rtt[algo] = process_rtt_files(data_dir, runs, algo)
    pcap_df = pd.DataFrame.from_dict(host_rtt, orient='index')
    pcap_df = pd.melt(pcap_df.reset_index(),
                      id_vars='index',
                      var_name="Metric",
                      value_name="Average RTT (ms)")
    pcap_df = pcap_df.rename(columns={'index': 'Algorithm'})
    # Convert to milliseconds
    # pcap_df = pcap_df.div(1e6)
    fig = sns.catplot(x='Metric',
                      y='Average RTT (ms)',
                      hue="Algorithm",
                      data=pcap_df,
                      kind='bar')
    from itertools import cycle
    hatches = cycle(["/", "-", "+", "x", '-', '+', 'x', 'O', '.'])

    num_locations = len(pcap_df.Metric.unique())
    for i, patch in enumerate(fig.ax.patches):
        # Blue bars first, then green bars
        if i % num_locations == 0:
            hatch = next(hatches)
        patch.set_hatch(hatch)
    plt_name += "_rtt"
    log.info("Saving plot %s", plt_name)
    plt.savefig(plt_name + ".png", bbox_inches='tight', pad_inches=0.05)
    plt.savefig(plt_name + ".pdf", bbox_inches='tight', pad_inches=0.05)
    plt.gcf().clear()
//  [python]
res_all_pd.to_csv('pns_distinguish_res.csv')

# compare conditional pns

cond_col = [col for col in res_all_pd if col.startswith('cond')]
fig, ax = plt.subplots()
fig.set_size_inches(3,2)
ax = sns.boxplot(data=res_all_pd[cond_col], palette="pastel")
//  [python]
res_all_pd.to_csv('pns_distinguish_res.csv')

# compare conditional pns

cond_col = [col for col in res_all_pd if col.startswith('cond')]
fig, ax = plt.subplots()
fig.set_size_inches(3,2)
ax = sns.catplot(data=res_all_pd[cond_col], palette="pastel",kind="box")
//  [python]
def plot_rships(sim):
    layer_keys = list(sim['partners'].keys())
    snaps = sim.get_analyzer('snapshot')

    dfs = []
    years = []
    for year, people in snaps.snapshots.items():
        df = pd.DataFrame({'age':people.age[people.alive==True], 'sex':people.is_female[people.alive==True]})
        df['sex'].replace({True:'Female', False:'Male'}, inplace=True)
        df['Age Bin'] = pd.cut(df['age'], people.age_bin_edges, right=False)
        df['Year'] = year
        for lk, lkey in enumerate(layer_keys):
            df[lkey] = people.n_rships[lk, people.alive==True]
        dfs.append(df)
        years.append(year)
    
    df = pd.concat(dfs)
    dfm = df.melt(id_vars=['Age Bin', 'sex', 'Year'], value_vars=layer_keys, var_name='Layer', value_name='n_rships')
    g = sns.FacetGrid(data=dfm, col='Year', row='Layer', sharey=False, height=5, aspect=0.75)
    g.map(sns.barplot, 'Age Bin', 'n_rships', 'sex', palette='tab10')
    g.set_xticklabels(rotation=70)
    g.set_ylabels('Number of Relationships')
    g.fig.tight_layout()
    g.fig.subplots_adjust(top=0.9)
    g.fig.suptitle(sim.label)

    dfm_fem = dfm[(dfm['sex'] == 'Female') & (dfm['Year'] == years[-1])]
    h = sns.FacetGrid(data=dfm_fem, col='Layer', sharey=False, height=5, aspect=0.75)
    h.map(sns.boxplot, 'Age Bin', 'n_rships')
    h.set_xticklabels(rotation=70)
    h.set_ylabels('Number of Relationships')
    h.fig.tight_layout()
    h.fig.subplots_adjust(top=0.9)
    h.fig.suptitle(sim.label)
//  [python]
def plot_rships(sim):
    layer_keys = list(sim['partners'].keys())
    snaps = sim.get_analyzer('snapshot')

    dfs = []
    years = []
    for year, people in snaps.snapshots.items():
        df = pd.DataFrame({'age':people.age[people.alive==True], 'sex':people.is_female[people.alive==True]})
        df['sex'].replace({True:'Female', False:'Male'}, inplace=True)
        df['Age Bin'] = pd.cut(df['age'], people.age_bin_edges, right=False)
        df['Year'] = year
        for lk, lkey in enumerate(layer_keys):
            df[lkey] = people.n_rships[lk, people.alive==True]
        dfs.append(df)
        years.append(year)
    
    df = pd.concat(dfs)
    dfm = df.melt(id_vars=['Age Bin', 'sex', 'Year'], value_vars=layer_keys, var_name='Layer', value_name='n_rships')
    g = sns.catplot(data=dfm, kind='bar', x='Age Bin', y='n_rships', hue='sex', col='Year', row='Layer', sharey=False, height=5, aspect=0.75, legend_out=False, palette='tab10')
    g.tick_params(axis='x', which='both', rotation=70)
    g.set_ylabels('Number of Relationships')
    g.fig.tight_layout()
    g.fig.subplots_adjust(top=0.9)
    g.fig.suptitle(sim.label)

    dfm_fem = dfm[(dfm['sex'] == 'Female') & (dfm['Year'] == years[-1])]
    h = sns.catplot(data=dfm_fem, kind='box', x='Age Bin', y='n_rships', col='Layer', sharey=False,
                    height=5, aspect=0.75, legend_out=False)
    h.tick_params(axis='x', which='both', rotation=70)
    h.set_ylabels('Number of Relationships')
    h.fig.tight_layout()
    h.fig.subplots_adjust(top=0.9)
    h.fig.suptitle(sim.label)
//  [python]
def count_values(df, feature, title):
        """
        Plot of count of distinct values ​​of a feature

        Parameters
        ----------
        df      : pd.DataFrame
                  dataframe with the values
        feature : str
                  name of the feature to be counted
        title   : str
                  chart title

        Returns
        ----
        None
        """
        g = sns.countplot(x=feature, data=df)
        g.set_xticklabels(rotation=90)
        g = plt.title(title)
//  [python]
def count_values(df, feature, title):
        """
        Plot of count of distinct values ​​of a feature

        Parameters
        ----------
        df      : pd.DataFrame
                  dataframe with the values
        feature : str
                  name of the feature to be counted
        title   : str
                  chart title

        Returns
        ----
        None
        """
        g = sns.catplot(feature, data=df, aspect=4, kind="count")
        g.set_xticklabels(rotation=90)
        g = plt.title(title)
//  [python]
def plot_bar_chart(df, baseline, palette_name):
  df = df.copy()

  df, did_normalize = do_normalize(df, baseline)

  hueCol = 'flags'
  numHues = len(df[hueCol].unique())

  if palette_name == "cubehelix":
    palette = sns.cubehelix_palette(numHues)
  else:
    palette = sns.color_palette(palette_name, numHues)

  g = sns.factorplot(data=df, kind='bar', x='program', y='time',
                  hue=hueCol, palette=palette, errwidth=1.125, capsize=0.0625,
                  legend_out=False)

  yMin = 0.5
  yMax = 1.5

  plt.ylim(yMin, yMax)

  axis = g.axes.flat[0]  # i think this is y axis?? whatever. it works
  add_value_labels(axis)

  leg = axis.get_legend()
  new_title = ''
  leg.set_title(new_title)

  yaxis_label = "Speedup" if did_normalize else "Time"
  g.set_axis_labels(x_var="", y_var=yaxis_label)

  plt.xticks(rotation=20)

  export_fig(g, "bars", None, [], lineplot=False)
//  [python]
def plot_bar_chart(df, baseline, palette_name):
  df = df.copy()

  df, did_normalize = do_normalize(df, baseline)

  hueCol = 'flags'
  numHues = len(df[hueCol].unique())

  if palette_name == "cubehelix":
    palette = sns.cubehelix_palette(numHues)
  else:
    palette = sns.color_palette(palette_name, numHues)

  g = sns.catplot(data=df, kind='bar', x='program', y='time',
                  hue=hueCol, palette=palette, errwidth=1.125, capsize=0.0625,
                  legend_out=False)

  yMin = 0.5
  yMax = 1.5

  plt.ylim(yMin, yMax)

  axis = g.axes.flat[0]  # i think this is y axis?? whatever. it works
  add_value_labels(axis)

  leg = axis.get_legend()
  new_title = ''
  leg.set_title(new_title)

  yaxis_label = "Speedup" if did_normalize else "Time"
  g.set_axis_labels(x_var="", y_var=yaxis_label)

  plt.xticks(rotation=20)

  export_fig(g, "bars", None, [], lineplot=False)
//  [python]
def my_catplot(df, var="var", x="x", hue="domain", func=None, bin=100, is_sort=False, xrotation=0, yrotation=0, is_count=True):

    ax = sns.violinplot(data=df, x="duration_s", hue="domain", bw=.25, cut=0, split=True)
    plt.savefig(f'cat_{var}_统计图.pdf', bbox_inches='tight', pad_inches=0)
    plt.savefig(f'cat_{var}_统计图.png', bbox_inches='tight', pad_inches=0)

    plt.show()
    plt.close()
//  [python]
def my_catplot(df, var="var", x="x", hue="domain", func=None, bin=100, is_sort=False, xrotation=0, yrotation=0, is_count=True):

    ax = sns.catplot(data=df, x="duration_s", hue="domain", kind="violin", bw=.25, cut=0, split=True)
    plt.savefig(f'cat_{var}_统计图.pdf', bbox_inches='tight', pad_inches=0)
    plt.savefig(f'cat_{var}_统计图.png', bbox_inches='tight', pad_inches=0)

    plt.show()
    plt.close()
//  [python]
def plot_rf_distributions(rf_areas, plot_type='box'):
    """

    Parameters
    ----------
    rf_areas : dict
    plot_type : str, optional
        'box' | 'hist'

    Returns
    -------
    matplotlib.figure.Figure
        figure handle

    """

    # put results into dataframe for easier plotting
    results = []
    for sub_type, areas in rf_areas.items():
        for i, area in enumerate(areas):
            results.append(pd.DataFrame({
                'cluster_id': i,
                'area': area,
                'Subfield': sub_type.upper()}, index=[0]))
    results_pd = pd.concat(results, ignore_index=True)
    # leave out non-responsive clusters
    data_queried = results_pd[results_pd.area != 0]

    if plot_type == 'box':

        splt = sns.boxplot(
            x='Subfield', y='area', data=data_queried)
        splt.set_yscale('log')
        splt.set_ylabel('RF Area (pixels$^2$)')
        splt.set_ylim([1e-1, 1e4])

    elif plot_type == 'hist':
        bins = 10 ** (np.arange(-1, 4.25, 0.25))
        xmin = 1e-1
        xmax = 1e4
        ymin = 1e0
        ymax = 1e3
        splt = plt.figure(figsize=(12, 4))

        plt.subplot(121)
        plt.hist(data_queried[data_queried.Subfield == 'ON']['area'], bins=bins, log=True)
        plt.xlabel('RF Area (pixels)')
        plt.xscale('log')
        plt.xlim([xmin, xmax])
        plt.ylim([ymin, ymax])
        plt.ylabel('Cluster count')
        plt.title('ON Subfield')

        plt.subplot(122)
        plt.hist(data_queried[data_queried.Subfield == 'OFF']['area'], bins=bins, log=True)
        plt.xlabel('RF Area (pixels)')
        plt.xscale('log')
        plt.xlim([xmin, xmax])
        plt.ylim([ymin, ymax])
        plt.title('OFF Subfield')

    plt.show()

    return splt
//  [python]
def plot_rf_distributions(rf_areas, plot_type='box'):
    """

    Parameters
    ----------
    rf_areas : dict
    plot_type : str, optional
        'box' | 'hist'

    Returns
    -------
    matplotlib.figure.Figure
        figure handle

    """

    # put results into dataframe for easier plotting
    results = []
    for sub_type, areas in rf_areas.items():
        for i, area in enumerate(areas):
            results.append(pd.DataFrame({
                'cluster_id': i,
                'area': area,
                'Subfield': sub_type.upper()}, index=[0]))
    results_pd = pd.concat(results, ignore_index=True)
    # leave out non-responsive clusters
    data_queried = results_pd[results_pd.area != 0]

    if plot_type == 'box':

        splt = sns.catplot(
            x='Subfield', y='area', kind='box', data=data_queried)
        splt.fig.axes[0].set_yscale('log')
        splt.fig.axes[0].set_ylabel('RF Area (pixels$^2$)')
        splt.fig.axes[0].set_ylim([1e-1, 1e4])

    elif plot_type == 'hist':
        bins = 10 ** (np.arange(-1, 4.25, 0.25))
        xmin = 1e-1
        xmax = 1e4
        ymin = 1e0
        ymax = 1e3
        splt = plt.figure(figsize=(12, 4))

        plt.subplot(121)
        plt.hist(data_queried[data_queried.Subfield == 'ON']['area'], bins=bins, log=True)
        plt.xlabel('RF Area (pixels)')
        plt.xscale('log')
        plt.xlim([xmin, xmax])
        plt.ylim([ymin, ymax])
        plt.ylabel('Cluster count')
        plt.title('ON Subfield')

        plt.subplot(122)
        plt.hist(data_queried[data_queried.Subfield == 'OFF']['area'], bins=bins, log=True)
        plt.xlabel('RF Area (pixels)')
        plt.xscale('log')
        plt.xlim([xmin, xmax])
        plt.ylim([ymin, ymax])
        plt.title('OFF Subfield')

    plt.show()

    return splt
//  [python]
def scatter_optimized_classes(opt_captions,sim_fooling,sim_imagenet_opt, path):
    df_input = [(key, inner_value, 'ImageNet') for key, value_lst in sim_imagenet_opt.items() for inner_value in
                value_lst]

    df_sim_imagenet = pd.DataFrame(df_input, columns=['class','CLIP Score','type'])
    df_sim_fooling = pd.DataFrame(zip(opt_captions,sim_fooling.flatten(order='F').tolist()),columns=['class', 'CLIP Score'])
    df_sim_fooling['type'] = len(opt_captions) * ['Fooling image']

    df_sim = pd.concat([df_sim_imagenet, df_sim_fooling])
    df_sim['class (short)'] = df_sim['class'].str.split(',').apply(lambda x: x[0])

    sns.set_context("paper")
    #plt.rcParams.update(params)

    plt.figure()
    sns_plot = sns.stripplot(data=df_sim, x="class (short)", y="CLIP Score", hue='type',
                           palette=sns.color_palette('colorblind', n_colors=2), legend=False)
    _ = plt.xticks(rotation=90)
    plt.legend()
    plt.tight_layout()
    plt.show()
    plt.savefig(path, dpi=300)
//  [python]
def scatter_optimized_classes(opt_captions,sim_fooling,sim_imagenet_opt, path):
    df_input = [(key, inner_value, 'ImageNet') for key, value_lst in sim_imagenet_opt.items() for inner_value in
                value_lst]

    df_sim_imagenet = pd.DataFrame(df_input, columns=['class','CLIP Score','type'])
    df_sim_fooling = pd.DataFrame(zip(opt_captions,sim_fooling.flatten(order='F').tolist()),columns=['class', 'CLIP Score'])
    df_sim_fooling['type'] = len(opt_captions) * ['Fooling image']

    df_sim = pd.concat([df_sim_imagenet, df_sim_fooling])
    df_sim['class (short)'] = df_sim['class'].str.split(',').apply(lambda x: x[0])

    sns.set_context("paper")
    #plt.rcParams.update(params)

    plt.figure()
    sns_plot = sns.catplot(data=df_sim, kind="strip", x="class (short)", y="CLIP Score", hue='type',
                           palette=sns.color_palette('colorblind', n_colors=2), legend=False, height=3.15, aspect=0.875)
    _ = plt.xticks(rotation=90)
    plt.legend()
    plt.tight_layout()
    plt.show()
    sns_plot.savefig(path, dpi=300)
//  [python]
def plot(test_results = None):
	palette = ["#b3b3b3", "#fff08a", "#83deed", "#8ad09d", "#cc95fa", "#f6958f"]
	workingpwd = os.getcwd()
	os.chdir(pwd)
	os.chdir(args.output_dir)
	df = pd.DataFrame(test_results)
	sns.set_theme(style="whitegrid")
	# penguins = sns.load_dataset("penguins")
	# Draw a nested barplot by species and sex

	def merge_show():
		g = sns.factorplot(
			data=df, kind="bar",
			x="task_name", y=args.metric, hue="method",
			errorbar="sd" if args.errorbar else None, palette=palette, alpha=.6, size=6
		)
		g.set(ylim=args.ylim)
		ax = g.facet_axis(0, 0)  # or ax = g.axes.flat[0]
		for c in ax.containers:
			labels = [f'{round(v.get_height()) if args.method_names == "StepNumber" else (v.get_height()):.2f}' for v in c]
			ax.bar_label(c, labels=labels, label_type='edge')

		g.despine(left=True)
		g.set_axis_labels("", args.metric)
		g.set_xticklabels(ax.get_xticklabels(),rotation = 20)
		g.legend.set_title("")

		#put hue from right to the top
		g.legend.remove()
		plt.legend(title="Method", bbox_to_anchor=(0.5, 1.15), loc="center", ncol=args.ncol)
		plt.gcf().subplots_adjust(top=0.8)
		# plt.show()
		print('save to', f'{"remove_comm_" if args.remove_comm_action else ""}{args.metric}_plot.png')
		plt.savefig(f'{"remove_comm_" if args.remove_comm_action else ""}{args.metric}_plot.png')
		plt.close()

	def split_show():
		grouped = df.groupby('env_id')
		# create an empty list to save grouped tables
		grouped_tables = []

		for name, group in grouped:
			grouped_tables.append(group)
		for plotdf in grouped_tables:
			g = sns.factorplot(
				data=plotdf, kind="bar",
				x="task_name", y=args.metric, hue="method",
				errorbar="sd" if args.errorbar else None, palette=palette, alpha=.6, size=6
			)
			g.set(ylim=args.ylim)
			ax = g.facet_axis(0, 0)  # or ax = g.axes.flat[0]
			for c in ax.containers:
				labels = [f'{round(v.get_height()) if args.method_names == "StepNumber" else (v.get_height()):.2f}' for v in c]
				ax.bar_label(c, labels=labels, label_type='edge')

			g.despine(left=True)
			g.set_axis_labels("", args.metric)
			g.set_xticklabels(ax.get_xticklabels(),rotation = 20)
			g.legend.set_title("")
			#put hue from right to the top
			g.legend.remove()
			plt.legend(bbox_to_anchor=(0.5, 1.15), loc="center", ncol=args.ncol)
			env_id = plotdf.iloc[0]['env_id']
			plt.title(f"Apt.{env_id}")
			plt.gcf().subplots_adjust(left=args.left, right=args.right, bottom=args.bottom, top=args.top)
			print('save to', f'{"remove_comm_" if args.remove_comm_action else ""}{args.metric}_{env_id}.png')
			plt.savefig(f'{"remove_comm_" if args.remove_comm_action else ""}{args.metric}_{env_id}.png')
			plt.close()
	print('-------------------------------------------------------')
	print('plotting...')
	if not args.split_show:
		merge_show()
	else:
		split_show()
	os.chdir(workingpwd)
//  [python]
def plot(test_results = None):
	palette = ["#b3b3b3", "#fff08a", "#83deed", "#8ad09d", "#cc95fa", "#f6958f"]
	workingpwd = os.getcwd()
	os.chdir(pwd)
	os.chdir(args.output_dir)
	df = pd.DataFrame(test_results)
	sns.set_theme(style="whitegrid")
	# penguins = sns.load_dataset("penguins")
	# Draw a nested barplot by species and sex

	def merge_show():
		g = sns.catplot(
			data=df, kind="bar",
			x="task_name", y=args.metric, hue="method",
			errorbar="sd" if args.errorbar else None, palette=palette, alpha=.6, height=6
		)
		g.set(ylim=args.ylim)
		ax = g.facet_axis(0, 0)  # or ax = g.axes.flat[0]
		for c in ax.containers:
			labels = [f'{round(v.get_height()) if args.method_names == "StepNumber" else (v.get_height()):.2f}' for v in c]
			ax.bar_label(c, labels=labels, label_type='edge')

		g.despine(left=True)
		g.set_axis_labels("", args.metric)
		g.set_xticklabels(ax.get_xticklabels(),rotation = 20)
		g.legend.set_title("")

		#put hue from right to the top
		g.legend.remove()
		plt.legend(title="Method", bbox_to_anchor=(0.5, 1.15), loc="center", ncol=args.ncol)
		plt.gcf().subplots_adjust(top=0.8)
		# plt.show()
		print('save to', f'{"remove_comm_" if args.remove_comm_action else ""}{args.metric}_plot.png')
		plt.savefig(f'{"remove_comm_" if args.remove_comm_action else ""}{args.metric}_plot.png')
		plt.close()

	def split_show():
		grouped = df.groupby('env_id')
		# create an empty list to save grouped tables
		grouped_tables = []

		for name, group in grouped:
			grouped_tables.append(group)
		for plotdf in grouped_tables:
			g = sns.catplot(
				data=plotdf, kind="bar",
				x="task_name", y=args.metric, hue="method",
				errorbar="sd" if args.errorbar else None, palette=palette, alpha=.6, height=6
			)
			g.set(ylim=args.ylim)
			ax = g.facet_axis(0, 0)  # or ax = g.axes.flat[0]
			for c in ax.containers:
				labels = [f'{round(v.get_height()) if args.method_names == "StepNumber" else (v.get_height()):.2f}' for v in c]
				ax.bar_label(c, labels=labels, label_type='edge')

			g.despine(left=True)
			g.set_axis_labels("", args.metric)
			g.set_xticklabels(ax.get_xticklabels(),rotation = 20)
			g.legend.set_title("")
			#put hue from right to the top
			g.legend.remove()
			plt.legend(bbox_to_anchor=(0.5, 1.15), loc="center", ncol=args.ncol)
			env_id = plotdf.iloc[0]['env_id']
			plt.title(f"Apt.{env_id}")
			plt.gcf().subplots_adjust(left=args.left, right=args.right, bottom=args.bottom, top=args.top)
			print('save to', f'{"remove_comm_" if args.remove_comm_action else ""}{args.metric}_{env_id}.png')
			plt.savefig(f'{"remove_comm_" if args.remove_comm_action else ""}{args.metric}_{env_id}.png')
			plt.close()
	print('-------------------------------------------------------')
	print('plotting...')
	if not args.split_show:
		merge_show()
	else:
		split_show()
	os.chdir(workingpwd)
//  [python]
oatvar = faraway.datasets.oatvar.load()
oatvar.pivot(index = 'variety', columns='block', values='yield')


#	

sns.boxplot(x="variety", y="yield", data=oatvar)
sns.boxplot(x="block", y="yield", data=oatvar)
sns.factorplot(x='variety',y='yield',hue='block', data=oatvar, 
   kind='point')
//  [python]
oatvar = faraway.datasets.oatvar.load()
oatvar.pivot(index = 'variety', columns='block', values='yield')


#	

sns.boxplot(x="variety", y="yield", data=oatvar)
sns.boxplot(x="block", y="yield", data=oatvar)
sns.catplot(x='variety',y='yield',hue='block', data=oatvar, 
   kind='point')
//  [python]
def scatter_optimized_classes_multi(opt_captions, similarities_fooling, similarities_imagenet, path):

    df_imagenet = [(key, inner_value, 'ImageNet') for key, value_lst in similarities_imagenet.items() for inner_value in
                value_lst]

    df_sim_imagenet = pd.DataFrame(df_imagenet, columns=['class', 'CLIP score', 'type'])
    all_frames = [df_sim_imagenet]
    for (sim_name,sim_vector) in similarities_fooling:
        df_sim = pd.DataFrame(zip(opt_captions, sim_vector.flatten(order='F').tolist()),
                                      columns=['class', 'CLIP score'])
        df_sim['type'] = len(opt_captions) * [sim_name]
        all_frames.append(df_sim)

    df_sim = pd.concat(all_frames)
    df_sim.reset_index(inplace=True)
    df_sim['class (short)'] = df_sim['class'].str.split(',').apply(lambda x: x[0])
    #df_sim.to_json('ImagenetScatter.json')

    sns.set_context("paper") 
    plt.rcParams.update(params)

    plt.figure()
    sns_plot = sns.stripplot(data=df_sim, x="class (short)", y="CLIP score", hue='type',
                           palette=sns.color_palette('colorblind', n_colors=len(similarities_fooling)+1), legend=False ,size=4, aspect=0.875)
    _ = plt.xticks(rotation=90)
    #sns.move_legend(sns_plot,loc='lower left')#, bbox_to_anchor=(5., 5.), title='type')
    plt.legend(loc='lower left')
    plt.tight_layout()
    plt.show()
    sns_plot.savefig(path, dpi=300)
//  [python]
def scatter_optimized_classes_multi(opt_captions, similarities_fooling, similarities_imagenet, path):

    df_imagenet = [(key, inner_value, 'ImageNet') for key, value_lst in similarities_imagenet.items() for inner_value in
                value_lst]

    df_sim_imagenet = pd.DataFrame(df_imagenet, columns=['class', 'CLIP score', 'type'])
    all_frames = [df_sim_imagenet]
    for (sim_name,sim_vector) in similarities_fooling:
        df_sim = pd.DataFrame(zip(opt_captions, sim_vector.flatten(order='F').tolist()),
                                      columns=['class', 'CLIP score'])
        df_sim['type'] = len(opt_captions) * [sim_name]
        all_frames.append(df_sim)

    df_sim = pd.concat(all_frames)
    df_sim.reset_index(inplace=True)
    df_sim['class (short)'] = df_sim['class'].str.split(',').apply(lambda x: x[0])
    #df_sim.to_json('ImagenetScatter.json')

    sns.set_context("paper") 
    plt.rcParams.update(params)

    plt.figure()
    sns_plot = sns.catplot(data=df_sim, kind="strip", x="class (short)", y="CLIP score", hue='type',
                           palette=sns.color_palette('colorblind', n_colors=len(similarities_fooling)+1), legend=False ,height=4, aspect=0.875)
    _ = plt.xticks(rotation=90)
    #sns.move_legend(sns_plot,loc='lower left')#, bbox_to_anchor=(5., 5.), title='type')
    plt.legend(loc='lower left')
    plt.tight_layout()
    plt.show()
    sns_plot.savefig(path, dpi=300)
//  [python]
def plot_against_tuple(data):
    """ Plot a bar graph of flops against tuple comparing fast_div performance. """

    def _get_title(data):
        main_title = 'Flops with and without fast_div'
        return get_conv_title(data, main_title)

    if (len(data.index) == 0):
        print("Skipping plot, as dataframe is empty")
        return

    fg = sns.factorplot(
        x='tuple', y='items_per_second', data=data, hue='fast_div', kind='bar')
    fg.set_axis_labels('(tile_rows, tile_cols, ch_vector, feat_vector)',
                       'Flops')
    fg.ax.set_xticklabels(fg.ax.get_xticklabels(), rotation=90)
    fg.fig.subplots_adjust(top=0.9)
    fg.fig.suptitle(_get_title(data))
    return fg
//  [python]
def plot_against_tuple(data):
    """ Plot a bar graph of flops against tuple comparing fast_div performance. """

    def _get_title(data):
        main_title = 'Flops with and without fast_div'
        return get_conv_title(data, main_title)

    if (len(data.index) == 0):
        print("Skipping plot, as dataframe is empty")
        return

    fg = sns.catplot(
        x='tuple', y='items_per_second', data=data, hue='fast_div', kind='bar')
    fg.set_axis_labels('(tile_rows, tile_cols, ch_vector, feat_vector)',
                       'Flops')
    fg.ax.set_xticklabels(fg.ax.get_xticklabels(), rotation=90)
    fg.fig.subplots_adjust(top=0.9)
    fg.fig.suptitle(_get_title(data))
    return fg
//  [python]
def plot_rf_distributions(rf_areas, plot_type='box'):
    """
    :param rf_areas:
    :param plot_type: 'box' | 'hist'
    :return: figure handle
    """

    # put results into dataframe for easier plotting
    results = []
    for sub_type, areas in rf_areas.items():
        for i, area in enumerate(areas):
            results.append(pd.DataFrame({
                'cluster_id': i,
                'area': area,
                'Subfield': sub_type.upper()}, index=[0]))
    results_pd = pd.concat(results, ignore_index=True)
    # leave out non-responsive clusters
    data_queried = results_pd[results_pd.area != 0]

    if plot_type == 'box':

        splt = sns.boxplot(
            x='Subfield', y='area', data=data_queried)
        splt.set_yscale('log')
        splt.set_ylabel('RF Area (pixels$^2$)')
        splt.set_ylim([1e-1, 1e4])

    elif plot_type == 'hist':
        bins = 10 ** (np.arange(-1, 4.25, 0.25))
        xmin = 1e-1
        xmax = 1e4
        ymin = 1e0
        ymax = 1e3
        splt = plt.figure(figsize=(12, 4))

        plt.subplot(121)
        plt.hist(data_queried[data_queried.Subfield == 'ON']['area'], bins=bins, log=True)
        plt.xlabel('RF Area (pixels)')
        plt.xscale('log')
        plt.xlim([xmin, xmax])
        plt.ylim([ymin, ymax])
        plt.ylabel('Cluster count')
        plt.title('ON Subfield')

        plt.subplot(122)
        plt.hist(data_queried[data_queried.Subfield == 'OFF']['area'], bins=bins, log=True)
        plt.xlabel('RF Area (pixels)')
        plt.xscale('log')
        plt.xlim([xmin, xmax])
        plt.ylim([ymin, ymax])
        plt.title('OFF Subfield')

    plt.show()

    return splt
//  [python]
def plot_rf_distributions(rf_areas, plot_type='box'):
    """
    :param rf_areas:
    :param plot_type: 'box' | 'hist'
    :return: figure handle
    """

    # put results into dataframe for easier plotting
    results = []
    for sub_type, areas in rf_areas.items():
        for i, area in enumerate(areas):
            results.append(pd.DataFrame({
                'cluster_id': i,
                'area': area,
                'Subfield': sub_type.upper()}, index=[0]))
    results_pd = pd.concat(results, ignore_index=True)
    # leave out non-responsive clusters
    data_queried = results_pd[results_pd.area != 0]

    if plot_type == 'box':

        splt = sns.catplot(
            x='Subfield', y='area', kind='box', data=data_queried)
        splt.fig.axes[0].set_yscale('log')
        splt.fig.axes[0].set_ylabel('RF Area (pixels$^2$)')
        splt.fig.axes[0].set_ylim([1e-1, 1e4])

    elif plot_type == 'hist':
        bins = 10 ** (np.arange(-1, 4.25, 0.25))
        xmin = 1e-1
        xmax = 1e4
        ymin = 1e0
        ymax = 1e3
        splt = plt.figure(figsize=(12, 4))

        plt.subplot(121)
        plt.hist(data_queried[data_queried.Subfield == 'ON']['area'], bins=bins, log=True)
        plt.xlabel('RF Area (pixels)')
        plt.xscale('log')
        plt.xlim([xmin, xmax])
        plt.ylim([ymin, ymax])
        plt.ylabel('Cluster count')
        plt.title('ON Subfield')

        plt.subplot(122)
        plt.hist(data_queried[data_queried.Subfield == 'OFF']['area'], bins=bins, log=True)
        plt.xlabel('RF Area (pixels)')
        plt.xscale('log')
        plt.xlim([xmin, xmax])
        plt.ylim([ymin, ymax])
        plt.title('OFF Subfield')

    plt.show()

    return splt
//  [python]
def plot_simulation_predictive_performance(s_df,
                                           metric='R2',
                                           showfliers=False,
                                           model_order=None,
                                           add_hatches=False,
                                           row_order=None,
                                           col_order=None,
                                           col_wrap=3,
                                           palette='Set2'):

    g = sns.factorplot(x="Heritability",
                    y=metric,
                    hue="Model",
                    col="Simulation model",
                    data=s_df,
                    kind="box",
                    showfliers=showfliers,
                    row_order=row_order,
                    col_order=col_order,
                    hue_order=model_order,
                    col_wrap=col_wrap,
                    palette=palette)

    if metric_name is not None:
        g.set_axis_labels("Heritability", metric_name(metric))

    if add_hatches:
        add_hatch_to_facet_plot(g, patch_index=[0, 1], kind="box")

    # Update the subplot titles:
    for fig_ax in g.fig.axes:
        fig_ax.set_title(fig_ax.get_title().replace("Simulation model = ", ""))

    return g
//  [python]
def plot_simulation_predictive_performance(s_df,
                                           metric='R2',
                                           showfliers=False,
                                           model_order=None,
                                           add_hatches=False,
                                           row_order=None,
                                           col_order=None,
                                           col_wrap=3,
                                           palette='Set2'):

    g = sns.catplot(x="Heritability",
                    y=metric,
                    hue="Model",
                    col="Simulation model",
                    data=s_df,
                    kind="box",
                    showfliers=showfliers,
                    row_order=row_order,
                    col_order=col_order,
                    hue_order=model_order,
                    col_wrap=col_wrap,
                    palette=palette)

    if metric_name is not None:
        g.set_axis_labels("Heritability", metric_name(metric))

    if add_hatches:
        add_hatch_to_facet_plot(g, patch_index=[0, 1], kind="box")

    # Update the subplot titles:
    for fig_ax in g.fig.axes:
        fig_ax.set_title(fig_ax.get_title().replace("Simulation model = ", ""))

    return g
//  [python]
def plot_real_predictive_performance(r_df, metric='R2',
                                     add_bar_labels=True,
                                     add_hatches=False,
                                     x_label_rotation=90,
                                     hide_x_labels=False,
                                     model_order=None, row_order=None, col_order=None,
                                     col_wrap=3, palette='Set2'):

    g = sns.factorplot(x="Model",
                    y=metric,
                    col="Trait",
                    data=r_df,
                    kind="bar",
                    col_wrap=col_wrap,
                    order=model_order,
                    row_order=row_order,
                    col_order=col_order,
                    palette=palette)

    if metric == 'ROC-AUC':
        for fig_ax in g.fig.axes:
            fig_ax.set_ylim(.5, 1.)

    if add_bar_labels:
        add_labels_to_bars(g)

    if add_hatches:
        add_hatch_to_facet_plot(g, patch_index=[0, 1])

    if x_label_rotation != 0 or hide_x_labels:
        for fig_ax in g.fig.axes:
            if hide_x_labels:
                fig_ax.set_xticklabels([])
            else:
                fig_ax.set_xticklabels(fig_ax.get_xticklabels(), rotation=x_label_rotation)

    # Update the subplot titles:
    for fig_ax in g.fig.axes:
        fig_ax.set_title(fig_ax.get_title().replace("Trait = ", ""))

    g.set_axis_labels("Model", metric_name(metric))

    return g
//  [python]
def plot_real_predictive_performance(r_df, metric='R2',
                                     add_bar_labels=True,
                                     add_hatches=False,
                                     x_label_rotation=90,
                                     hide_x_labels=False,
                                     model_order=None, row_order=None, col_order=None,
                                     col_wrap=3, palette='Set2'):

    g = sns.catplot(x="Model",
                    y=metric,
                    col="Trait",
                    data=r_df,
                    kind="bar",
                    col_wrap=col_wrap,
                    order=model_order,
                    row_order=row_order,
                    col_order=col_order,
                    palette=palette)

    if metric == 'ROC-AUC':
        for fig_ax in g.fig.axes:
            fig_ax.set_ylim(.5, 1.)

    if add_bar_labels:
        add_labels_to_bars(g)

    if add_hatches:
        add_hatch_to_facet_plot(g, patch_index=[0, 1])

    if x_label_rotation != 0 or hide_x_labels:
        for fig_ax in g.fig.axes:
            if hide_x_labels:
                fig_ax.set_xticklabels([])
            else:
                fig_ax.set_xticklabels(fig_ax.get_xticklabels(), rotation=x_label_rotation)

    # Update the subplot titles:
    for fig_ax in g.fig.axes:
        fig_ax.set_title(fig_ax.get_title().replace("Trait = ", ""))

    g.set_axis_labels("Model", metric_name(metric))

    return g
//  [python]
def get_plots(bias_dict):
    #tuple_community = []
    for each_method in ['bnsp', 'subgroup', 'bpsn']:
        tuple_community = []
        for each_model in bias_dict:
            # Select the metric which you want to view. Possible values are subgroup, bpsn, bnsp
            #each_method = 'bnsp' 
            
            for each_community in bias_dict[each_model][each_method]:
                tuple_community.append((each_model, each_community, bias_dict[each_model][each_method][each_community]))
        
        df_community_score = pd.DataFrame(tuple_community, columns=['Model', 'Community', 'AUCROC'])

        ax = sns.factorplot(x="Community", y="AUCROC", hue="Model",
                    data=df_community_score,
                    legend=False,
                    kind="bar")
        ax.set(ylim=(0.3, 1.0))
        ax.set_xticklabels(rotation=45, size=13, horizontalalignment='right')

        # sns.set(font_scale = 0.1)

        handles = ax._legend_data.values()
        labels = ax._legend_data.keys()

        ax.fig.legend(handles=handles, labels=labels, loc='upper right', ncol=3)
        ax.fig.subplots_adjust(top=0.92)

        #ax.set(xlabel=each_method.upper(), fontdict={'fontsize': 15, 'fontweight': 'bold'}, pad=15)  
        plt.xlabel(xlabel=each_method.upper(), fontdict={'fontsize': 15, 'fontweight': 'bold'}, labelpad=5)  
        #plt.title(each_method.upper(), loc='left', fontdict={'fontsize': 15}, pad=15)
        #print(each_method)
        plt.savefig('/home/jiyun/hatesp_detection/vis/bias_'+each_method+'.png', dpi=300, transparent=True, bbox_inches='tight')
//  [python]
def get_plots(bias_dict):
    #tuple_community = []
    for each_method in ['bnsp', 'subgroup', 'bpsn']:
        tuple_community = []
        for each_model in bias_dict:
            # Select the metric which you want to view. Possible values are subgroup, bpsn, bnsp
            #each_method = 'bnsp' 
            
            for each_community in bias_dict[each_model][each_method]:
                tuple_community.append((each_model, each_community, bias_dict[each_model][each_method][each_community]))
        
        df_community_score = pd.DataFrame(tuple_community, columns=['Model', 'Community', 'AUCROC'])

        ax = sns.catplot(x="Community", y="AUCROC", hue="Model",
                    data=df_community_score,
                    legend=False,
                    kind="bar")
        ax.set(ylim=(0.3, 1.0))
        ax.set_xticklabels(rotation=45, size=13, horizontalalignment='right')

        # sns.set(font_scale = 0.1)

        handles = ax._legend_data.values()
        labels = ax._legend_data.keys()

        ax.fig.legend(handles=handles, labels=labels, loc='upper right', ncol=3)
        ax.fig.subplots_adjust(top=0.92)

        #ax.set(xlabel=each_method.upper(), fontdict={'fontsize': 15, 'fontweight': 'bold'}, pad=15)  
        plt.xlabel(xlabel=each_method.upper(), fontdict={'fontsize': 15, 'fontweight': 'bold'}, labelpad=5)  
        #plt.title(each_method.upper(), loc='left', fontdict={'fontsize': 15}, pad=15)
        #print(each_method)
        plt.savefig('/home/jiyun/hatesp_detection/vis/bias_'+each_method+'.png', dpi=300, transparent=True, bbox_inches='tight')
//  [python]
def stats_active_blipp_users(request):
    
    f = OrderFilter(request.GET, queryset=models.Order.objects.all())

    orders = f.qs.filter(
        accepted=True
    ).annotate(week=F("put_at__week"), year=F("put_at__year")).order_by("year", "week").values("week", "year").annotate(num_users=Count("user_id", distinct=True)).annotate(num_purchases=Count("id"))
    
    orders_data = []
    for data in orders:
        orders_data.append({
                "when": f"{data['week']}-{data['year']} ({round(data['num_purchases']/data['num_users'], 1)})",
                "num_users": data["num_users"],
                "num_purchases": data["num_purchases"],
                "avg_purchases": data["num_purchases"]/data["num_users"]
            })
    order_data = DataFrame(data=orders_data)

    sns.set_theme()
    plt.figure(figsize = (16,9))
    plot = sns.barplot(data=order_data, y="when", x="num_users")
    plot.set_ylabel("När (Antal köp per användare)")
    plot.set_xlabel("Antal användare")
    buffer = BytesIO() 
    plot.figure.savefig(buffer, format='png')
    buffer.seek(0)
    #return FileResponse(buffer, filename='blippstats.png')
    tpl = {
        "image_data": f"data:image/png;base64,{base64.b64encode(buffer.read()).decode()}",
        "filter": f
    }
    return render(request, 'baljan/stat_plot.html', tpl)
//  [python]
def stats_active_blipp_users(request):
    
    f = OrderFilter(request.GET, queryset=models.Order.objects.all())

    orders = f.qs.filter(
        accepted=True
    ).annotate(week=F("put_at__week"), year=F("put_at__year")).order_by("year", "week").values("week", "year").annotate(num_users=Count("user_id", distinct=True)).annotate(num_purchases=Count("id"))
    
    orders_data = []
    for data in orders:
        orders_data.append({
                "when": f"{data['week']}-{data['year']} ({round(data['num_purchases']/data['num_users'], 1)})",
                "num_users": data["num_users"],
                "num_purchases": data["num_purchases"],
                "avg_purchases": data["num_purchases"]/data["num_users"]
            })
    order_data = DataFrame(data=orders_data)

    sns.set_theme()
    plt.figure(figsize = (16,9))
    plot = sns.catplot(data=order_data, y="when", x="num_users", kind="bar")
    plot.set_axis_labels("Antal användare", "När (Antal köp per användare)")
    buffer = BytesIO() 
    plot.savefig(buffer, format='png')
    buffer.seek(0)
    #return FileResponse(buffer, filename='blippstats.png')
    tpl = {
        "image_data": f"data:image/png;base64,{base64.b64encode(buffer.read()).decode()}",
        "filter": f
    }
    return render(request, 'baljan/stat_plot.html', tpl)
//  [python]
def plot_kernel_ite_comparison(treatment_effect_tracker, prefix=None):
  """Show that kernel choice does not matter. --> then continue w/ RBF."""
  range_accuracy = '0.0_1.0'
  # unique_hparam_types = treatment_effect_tracker['hparam_type'].unique()
  # for hparam_type in unique_hparam_types:
  for hparam_type in ['config.optimizer']:
    filtered = treatment_effect_tracker.where(
        (treatment_effect_tracker['hparam_type'] == hparam_type) &
        (treatment_effect_tracker['range_accuracy'] == range_accuracy)
    ).dropna()
    for target_type in ['explan']:
      g = sns.factorplot(
          x='explan_type',
          y='%s_ite' % target_type,
          hue='h1_h2_str',
          col='kernel_type',
          data=filtered,
          kind='violin',
          sharey=False,
          legend=False,
          # height=3,
          # gridspec_kws={"wspace":0.4},
      )
      g.fig.set_size_inches(14, 4)
      for ax_idx, ax in enumerate(g.axes[0]):
        if ax_idx == 0 and target_type == 'explan':
          ax.legend(
              loc='upper left',
              ncol=1,
              title='Hyperparameter',  # cfg.HPARAM_NAME_CONVERTER[hparam_type],
          )

      for ax_idx, ax in enumerate(g.axes.flatten()):
        # ax.set_xlabel('Explanation Type')
        ax.set_xlabel('')
        explan_type = ax.get_title().split('=')[1][1:]
        explan_type = config.KERNEL_NAME_CONVERTER[explan_type]
        ax.set_title(explan_type)
        if ax_idx == 0:
          ax.set_ylabel(r'$ITE_{E}(x)$', fontsize=14)
        else:
          ax.set_ylabel('')

      for ax_idx, ax in enumerate(g.axes.flatten()):
        labels = ax.get_xticklabels()
        for label in labels:
          label.set_text(config.EXPLAN_NAME_CONVERTER[label.get_text()])
        ax.set_xticklabels(labels)

      plt.subplots_adjust(hspace=0.1, wspace=0.1)
      prefix = 'kernel' if not prefix else prefix
      save_paper_figures(
          '%s_ite_comparison_%s_%s_%s_%s.png' %
          (prefix, config.cfg.DATASET, target_type, range_accuracy, hparam_type)
      )
//  [python]
def plot_kernel_ite_comparison(treatment_effect_tracker, prefix=None):
  """Show that kernel choice does not matter. --> then continue w/ RBF."""
  range_accuracy = '0.0_1.0'
  # unique_hparam_types = treatment_effect_tracker['hparam_type'].unique()
  # for hparam_type in unique_hparam_types:
  for hparam_type in ['config.optimizer']:
    filtered = treatment_effect_tracker.where(
        (treatment_effect_tracker['hparam_type'] == hparam_type) &
        (treatment_effect_tracker['range_accuracy'] == range_accuracy)
    ).dropna()
    for target_type in ['explan']:
      g = sns.catplot(
          x='explan_type',
          y='%s_ite' % target_type,
          hue='h1_h2_str',
          col='kernel_type',
          data=filtered,
          kind='violin',
          sharey=False,
          legend=False,
          # height=3,
          # gridspec_kws={"wspace":0.4},
      )
      g.fig.set_size_inches(14, 4)
      for ax_idx, ax in enumerate(g.axes[0]):
        if ax_idx == 0 and target_type == 'explan':
          ax.legend(
              loc='upper left',
              ncol=1,
              title='Hyperparameter',  # cfg.HPARAM_NAME_CONVERTER[hparam_type],
          )

      for ax_idx, ax in enumerate(g.axes.flatten()):
        # ax.set_xlabel('Explanation Type')
        ax.set_xlabel('')
        explan_type = ax.get_title().split('=')[1][1:]
        explan_type = config.KERNEL_NAME_CONVERTER[explan_type]
        ax.set_title(explan_type)
        if ax_idx == 0:
          ax.set_ylabel(r'$ITE_{E}(x)$', fontsize=14)
        else:
          ax.set_ylabel('')

      for ax_idx, ax in enumerate(g.axes.flatten()):
        labels = ax.get_xticklabels()
        for label in labels:
          label.set_text(config.EXPLAN_NAME_CONVERTER[label.get_text()])
        ax.set_xticklabels(labels)

      plt.subplots_adjust(hspace=0.1, wspace=0.1)
      prefix = 'kernel' if not prefix else prefix
      save_paper_figures(
          '%s_ite_comparison_%s_%s_%s_%s.png' %
          (prefix, config.cfg.DATASET, target_type, range_accuracy, hparam_type)
      )
//  [python]
def visualize_count(Xdata,
                    Xlayer = "raw_expr",
                    cell_anno_key = "cell_type",
                    region_key = "chr_arm",
                    chr_lst = ["1q"]
                    ):
    """
    """
    data_used = get_count_df(Xdata, Xlayer, cell_anno_key, region_key, chr_lst)
    
    # visualization
    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_anno_key, col_wrap=1, height=4, aspect=5)
    g.map(sns.boxplot, "bins_loc", "count", palette="Set3", fliersize=1, linewidth=1, whis=2)
    plt.show()
//  [python]
def visualize_count(Xdata,
                    Xlayer = "raw_expr",
                    cell_anno_key = "cell_type",
                    region_key = "chr_arm",
                    chr_lst = ["1q"]
                    ):
    """
    """
    data_used = get_count_df(Xdata, Xlayer, cell_anno_key, region_key, chr_lst)
    
    # visualization
    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_anno_key, kind="box",whis=2, 
                height=4, aspect=5, orient = "v", col_wrap =1)
    plt.show()
//  [python]
def get_subject_skeleton_volume_figure(self):
        """Subject skeleton volume figure """

        self.g_skel_vol = sns.factorplot(
                x='subject',
                y='skeleton_volume',
                data=self.df)

        self.g_skel_vol.fig.set_size_inches(8, 4)
        self.g_skel_vol.fig.set_dpi(150)
        self.g_skel_vol.ax.set_ylabel(f'{self.modality} skeleton volume')

        if len(self.df) > 100:
            for tick in self.g_skel_vol.ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(8)
        self.g_skel_vol.ax.set_xlabel('Subject')
        self.g_skel_vol.ax.set_title(
            f'Volume of {self.modality} skeleton for all subjects',
            fontweight='bold')

        # highlight the subject who are off the most common value
        most_common_volume = self.df['skeleton_volume'].value_counts().idxmax()
        for index, row in self.df.iterrows():
            if row.skeleton_volume != most_common_volume:
                self.g_skel_vol.ax.text(
                    index,
                    row.skeleton_volume,
                    row.subject, ha='center', va='center')
//  [python]
def get_subject_skeleton_volume_figure(self):
        """Subject skeleton volume figure """

        self.g_skel_vol = sns.catplot(
                x='subject',
                y='skeleton_volume',
                data=self.df)

        self.g_skel_vol.fig.set_size_inches(8, 4)
        self.g_skel_vol.fig.set_dpi(150)
        self.g_skel_vol.ax.set_ylabel(f'{self.modality} skeleton volume')

        if len(self.df) > 100:
            for tick in self.g_skel_vol.ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(8)
        self.g_skel_vol.ax.set_xlabel('Subject')
        self.g_skel_vol.ax.set_title(
            f'Volume of {self.modality} skeleton for all subjects',
            fontweight='bold')

        # highlight the subject who are off the most common value
        most_common_volume = self.df['skeleton_volume'].value_counts().idxmax()
        for index, row in self.df.iterrows():
            if row.skeleton_volume != most_common_volume:
                self.g_skel_vol.ax.text(
                    index,
                    row.skeleton_volume,
                    row.subject, ha='center', va='center')