jiahuimbzuai/CoQuIR huggingface dataset:
//  [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.catplot(
        data=data_frame, kind='violin',
        x=within_plot_categories, y=variable,
        col=plot_categories, col_wrap=2,
        height=panel_height, aspect=panel_aspect,
        cut=0, inner=None, native_scale=True
    )
    grid.map_dataframe(sns.swarmplot, data=data_frame,
                       x=within_plot_categories, y=variable,
                       size=2, native_scale=True, 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())
//  [python]
def residual_barplots(
        self,
        estimated_parameters: list[float],
        true_parameters: list[float],
        parameter_type: ParameterType,
    ) -> None:
        """
        Barplots showing estimated vs true Parameter
        values for each bandit.
        """
        parameters = estimated_parameters + true_parameters

        parameter_types = ["Estimated" for _ in range(len(self.bandit_collection))] + [
            "True" for _ in range(len(self.bandit_collection))
        ]

        bandit_id = [bandit.id for bandit in self.bandit_collection] * 2

        data = pd.DataFrame(
            {
                "Parameter Value": parameters,
                "Parameter Type": parameter_types,
                "Bandit ID": bandit_id,
            }
        )

        sns.set_theme(style="whitegrid")
        ax = sns.factorplot(
            data=data,
            x="Bandit ID",
            y="Parameter Value",
            hue="Parameter Type",
            kind="bar",
            alpha=0.8,
        )
        ax.despine(left=True)
        ax.set(
            title=f"Simulation Estimated {parameter_type} "
            f"vs True {parameter_type} Parameters"
        )
        plt.show()
//  [python]
def residual_barplots(
        self,
        estimated_parameters: list[float],
        true_parameters: list[float],
        parameter_type: ParameterType,
    ) -> None:
        """
        Barplots showing estimated vs true Parameter
        values for each bandit.
        """
        parameters = estimated_parameters + true_parameters

        parameter_types = ["Estimated" for _ in range(len(self.bandit_collection))] + [
            "True" for _ in range(len(self.bandit_collection))
        ]

        bandit_id = [bandit.id for bandit in self.bandit_collection] * 2

        data = pd.DataFrame(
            {
                "Parameter Value": parameters,
                "Parameter Type": parameter_types,
                "Bandit ID": bandit_id,
            }
        )

        sns.set_theme(style="whitegrid")
        ax = sns.catplot(
            data=data,
            x="Bandit ID",
            y="Parameter Value",
            hue="Parameter Type",
            kind="bar",
            alpha=0.8,
        )
        ax.despine(left=True)
        ax.set(
            title=f"Simulation Estimated {parameter_type} "
            f"vs True {parameter_type} Parameters"
        )
        plt.show()
//  [python]
def plot_results(df, target_lib="", audio_format="", ext="png"):
    sns.set_style("whitegrid")

    ordered_libs = df.time.groupby(df.lib).mean().sort_values().index.tolist()

    fig = plt.figure()

    g = sns.pointplot(
        x="duration",
        y="time",
        hue_order=ordered_libs,
        hue="lib",
        data=df,
    )

    g.figure.savefig("benchmark_%s_%s_dur.%s" % (target_lib, audio_format, ext))

    fig = plt.figure()
    sns.barplot(x="time", y="lib", data=df, order=ordered_libs, orient="h")
    fig.savefig(
        f"benchmark_{target_lib}_{audio_format}_bar.{ext}",
        bbox_inches="tight",
    )
//  [python]
def plot_results(df, target_lib="", audio_format="", ext="png"):
    sns.set_style("whitegrid")

    ordered_libs = df.time.groupby(df.lib).mean().sort_values().index.tolist()

    fig = plt.figure()

    g = sns.catplot(
        x="duration",
        y="time",
        kind="point",
        hue_order=ordered_libs,
        hue="lib",
        data=df,
        height=6.6,
        aspect=1,
    )

    g.savefig("benchmark_%s_%s_dur.%s" % (target_lib, audio_format, ext))

    fig = plt.figure()
    sns.barplot(x="time", y="lib", data=df, order=ordered_libs, orient="h")
    fig.savefig(
        f"benchmark_{target_lib}_{audio_format}_bar.{ext}",
        bbox_inches="tight",
    )
//  [python]
def plot_throughput_bar(
        self,
        data: pd.DataFrame,
        x_column="rate",
        row=None,
        col=None,
        # pylint: disable=dangerous-default-value
        ignore_vars=[],
        filename="",
    ):
        """
        Plot a bar graph of throughput.
        """
        hue = "vars"
        y_column = "achieved_throughput_ratio"

        var, invariant_vars = condense_vars(
            data, [x_column, y_column, row, col, hue] + ignore_vars
        )
        data[hue] = var
        # fill in missing values so that groupby works
        data[hue].fillna("", inplace=True)

        group_cols = [x_column, hue]
        if row:
            group_cols.append(row)
        if col:
            group_cols.append(col)
        data["rate2"] = data[x_column]
        grouped = data.groupby(group_cols)
        throughputs = grouped.first()

        durations = (grouped["end_ms"].max() - grouped["start_ms"].min()) / 1000
        counts = grouped["start_ms"].count()
        achieved_throughput = counts / durations

        throughputs[y_column] = achieved_throughput / throughputs["rate2"]

        throughputs.reset_index(inplace=True)

        plot = sns.factorplot(
            kind="bar",
            data=throughputs,
            x=x_column,
            y=y_column,
            row=row,
            col=col,
            hue=hue if not var.empty else None,
        )

        plot.figure.subplots_adjust(top=0.9)
        plot.figure.suptitle(make_title(invariant_vars))

        # add tick labels to each x axis
        for axes in plot.axes.flatten():
            axes.tick_params(labelbottom=True)

        if not filename:
            filename = f"throughput_bar-{x_column}-{row}-{col}-{hue}"

        plot.savefig(os.path.join(self.plot_dir(), f"{filename}.svg"))
        plot.savefig(os.path.join(self.plot_dir(), f"{filename}.jpg"))

        return plot
//  [python]
def plot_throughput_bar(
        self,
        data: pd.DataFrame,
        x_column="rate",
        row=None,
        col=None,
        # pylint: disable=dangerous-default-value
        ignore_vars=[],
        filename="",
    ):
        """
        Plot a bar graph of throughput.
        """
        hue = "vars"
        y_column = "achieved_throughput_ratio"

        var, invariant_vars = condense_vars(
            data, [x_column, y_column, row, col, hue] + ignore_vars
        )
        data[hue] = var
        # fill in missing values so that groupby works
        data[hue].fillna("", inplace=True)

        group_cols = [x_column, hue]
        if row:
            group_cols.append(row)
        if col:
            group_cols.append(col)
        data["rate2"] = data[x_column]
        grouped = data.groupby(group_cols)
        throughputs = grouped.first()

        durations = (grouped["end_ms"].max() - grouped["start_ms"].min()) / 1000
        counts = grouped["start_ms"].count()
        achieved_throughput = counts / durations

        throughputs[y_column] = achieved_throughput / throughputs["rate2"]

        throughputs.reset_index(inplace=True)

        plot = sns.catplot(
            kind="bar",
            data=throughputs,
            x=x_column,
            y=y_column,
            row=row,
            col=col,
            hue=hue if not var.empty else None,
        )

        plot.figure.subplots_adjust(top=0.9)
        plot.figure.suptitle(make_title(invariant_vars))

        # add tick labels to each x axis
        for axes in plot.axes.flatten():
            axes.tick_params(labelbottom=True)

        if not filename:
            filename = f"throughput_bar-{x_column}-{row}-{col}-{hue}"

        plot.savefig(os.path.join(self.plot_dir(), f"{filename}.svg"))
        plot.savefig(os.path.join(self.plot_dir(), f"{filename}.jpg"))

        return plot
//  [python]
def plot_achieved_throughput_bar(
        self,
        data: pd.DataFrame,
        x_column="vars",
        row=None,
        col=None,
        hue=None,
        # pylint: disable=dangerous-default-value
        ignore_vars=[],
        filename="",
    ):
        """
        Plot a bar graph of achieved throughput.
        """
        y_column = "achieved_throughput"

        var, invariant_vars = condense_vars(
            data, [x_column, y_column, row, col, hue] + ignore_vars
        )
        data["vars"] = var

        group_cols = [x_column]
        if row:
            group_cols.append(row)
        if col:
            group_cols.append(col)
        if hue:
            group_cols.append(hue)
        grouped = data.groupby(group_cols, dropna=False)
        throughputs = grouped.first()

        durations = (grouped["end_ms"].max() - grouped["start_ms"].min()) / 1000
        counts = grouped["start_ms"].count()
        achieved_throughput = counts / durations
        throughputs["achieved_throughput"] = achieved_throughput

        throughputs.reset_index(inplace=True)

        plot = sns.factorplot(
            kind="bar",
            data=throughputs,
            x=x_column,
            y=y_column,
            row=row,
            col=col,
        )

        plot.figure.subplots_adjust(top=0.9)
        plot.figure.suptitle(make_title(invariant_vars))

        # add tick labels to each x axis
        for axes in plot.axes.flatten():
            axes.tick_params(labelbottom=True)

        plot.set_xticklabels(rotation=30, horizontalalignment="right")
        plot.fig.tight_layout()

        if not filename:
            filename = f"achieved_throughput_bar-{x_column}-{row}-{col}"

        plot.savefig(os.path.join(self.plot_dir(), f"{filename}.svg"))
        plot.savefig(os.path.join(self.plot_dir(), f"{filename}.jpg"))

        return plot
//  [python]
def plot_achieved_throughput_bar(
        self,
        data: pd.DataFrame,
        x_column="vars",
        row=None,
        col=None,
        hue=None,
        # pylint: disable=dangerous-default-value
        ignore_vars=[],
        filename="",
    ):
        """
        Plot a bar graph of achieved throughput.
        """
        y_column = "achieved_throughput"

        var, invariant_vars = condense_vars(
            data, [x_column, y_column, row, col, hue] + ignore_vars
        )
        data["vars"] = var

        group_cols = [x_column]
        if row:
            group_cols.append(row)
        if col:
            group_cols.append(col)
        if hue:
            group_cols.append(hue)
        grouped = data.groupby(group_cols, dropna=False)
        throughputs = grouped.first()

        durations = (grouped["end_ms"].max() - grouped["start_ms"].min()) / 1000
        counts = grouped["start_ms"].count()
        achieved_throughput = counts / durations
        throughputs["achieved_throughput"] = achieved_throughput

        throughputs.reset_index(inplace=True)

        plot = sns.catplot(
            kind="bar",
            data=throughputs,
            x=x_column,
            y=y_column,
            row=row,
            col=col,
        )

        plot.figure.subplots_adjust(top=0.9)
        plot.figure.suptitle(make_title(invariant_vars))

        # add tick labels to each x axis
        for axes in plot.axes.flatten():
            axes.tick_params(labelbottom=True)

        plot.set_xticklabels(rotation=30, horizontalalignment="right")
        plot.fig.tight_layout()

        if not filename:
            filename = f"achieved_throughput_bar-{x_column}-{row}-{col}"

        plot.savefig(os.path.join(self.plot_dir(), f"{filename}.svg"))
        plot.savefig(os.path.join(self.plot_dir(), f"{filename}.jpg"))

        return plot
//  [python]
dv_all = (
    # 'rt', 'mt', 'movement_dist',  # because of how data collection is setup, RT, MT, and movement distance are not available
    'peak_vel', 'time_to_peak_vel', 'time_after_peak_vel',
    'peak_acc', 'time_to_peak_acc', 'time_after_peak_acc')

# iterate through all dependent measures and plot them
for dv in dv_all:
    sns.barplot(
        data=dv_output,

        x='vision',
        y=dv,
    )
    plt.suptitle(dv)
//  [python]
dv_all = (
    # 'rt', 'mt', 'movement_dist',  # because of how data collection is setup, RT, MT, and movement distance are not available
    'peak_vel', 'time_to_peak_vel', 'time_after_peak_vel',
    'peak_acc', 'time_to_peak_acc', 'time_after_peak_acc')

# iterate through all dependent measures and plot them
for dv in dv_all:
    sns.catplot(
        data=dv_output,

        x='vision',
        y=dv,

        kind='bar',
    )
    plt.suptitle(dv)
//  [python]
l_ncells=[100,200,500,1000]
MP3_results=[]

df = pd.read_csv("/home/e840r/Documents/COMPASS_project/out_simulations/ncells/results_BITSC2.csv",sep=",")

sns.set(font="Helvetica",font_scale=1.8)

g = sns.boxplot(x="ncells", y="MP3",data=df, hue="method",palette=["#FDC508"], #palette="Set1"
    showmeans=True,meanprops={"markersize":10,"marker":"X","markerfacecolor":"black", "markeredgecolor":"black"},
    fliersize=2)
//  [python]
l_ncells=[100,200,500,1000]
MP3_results=[]

df = pd.read_csv("/home/e840r/Documents/COMPASS_project/out_simulations/ncells/results_BITSC2.csv",sep=",")

sns.set(font="Helvetica",font_scale=1.8)

g = sns.catplot(x="ncells", y="MP3",data=df, kind="box",hue="method",palette=["#FDC508"], #palette="Set1"
    showmeans=True,meanprops={"markersize":10,"marker":"X","markerfacecolor":"black", "markeredgecolor":"black"},
    margin_titles=False,legend=False,fliersize=2,height=5,aspect=1.2)
//  [python]
a = list(df['type'])
for i in range(0, len(df)):
    if str(a[i][0]) == 'R' and a[i][1] == 'e':
        a[i] = 'Residential'
    elif str(a[i][0]) == 'I':
        a[i] = 'Industrial'
    else:
        a[i] = 'Other'
    
df['type'] = a
df['type'].value_counts()

######################################### do add threshold lines
#how many observations belong to each location
sns.countplot(x = "type", palette = "ch: 0.25", data = df)
//  [python]
a = list(df['type'])
for i in range(0, len(df)):
    if str(a[i][0]) == 'R' and a[i][1] == 'e':
        a[i] = 'Residential'
    elif str(a[i][0]) == 'I':
        a[i] = 'Industrial'
    else:
        a[i] = 'Other'
    
df['type'] = a
df['type'].value_counts()

######################################### do add threshold lines
#how many observations belong to each location
sns.catplot(x = "type", kind = "count", palette = "ch: 0.25", data = df)
//  [python]
def plot_metrics(df, x, y, hue, col, col_wrap=None, ylim=(0,1), aspect=1):
    g = sns.factorplot(x=x, y=y, data=df, hue=hue, col=col, col_wrap=col_wrap,
            size=set_size(width)[1], aspect=aspect, legend_out=False, kind='bar',
            saturation=.5, sharex=False, ci=None)
    g._legend.remove()
    handles, labels = g.fig.get_axes()[1].get_legend_handles_labels()
    g.fig.legend(handles=handles, labels=labels, loc='lower center', ncol=4,
            frameon=False)
    g.set_axis_labels('', 'Metric (\%)')
    g.set(ylim=ylim)
    g.despine(left=True)

    # Add annotations.
    for ax in g.axes.ravel():
        for c in ax.containers:
            labels = [f'{(v.get_height()):.2f}' for v in c]
            ax.bar_label(c, labels=labels, label_type='edge')
        ax.margins(y=0.2)
//  [python]
def plot_metrics(df, x, y, hue, col, col_wrap=None, ylim=(0,1), aspect=1):
    g = sns.catplot(x=x, y=y, data=df, hue=hue, col=col, col_wrap=col_wrap,
            height=set_size(width)[1], aspect=aspect, legend_out=False, kind='bar',
            saturation=.5, sharex=False, ci=None)
    g._legend.remove()
    handles, labels = g.fig.get_axes()[1].get_legend_handles_labels()
    g.fig.legend(handles=handles, labels=labels, loc='lower center', ncol=4,
            frameon=False)
    g.set_axis_labels('', 'Metric (\%)')
    g.set(ylim=ylim)
    g.despine(left=True)

    # Add annotations.
    for ax in g.axes.ravel():
        for c in ax.containers:
            labels = [f'{(v.get_height()):.2f}' for v in c]
            ax.bar_label(c, labels=labels, label_type='edge')
        ax.margins(y=0.2)
//  [python]
def _plot_results_accuracy_diff_scatter(results_df, save_cfg):
    """Plot difference in accuracy for each condition/task as a scatter plot.
    """
    fig, ax = plt.subplots(figsize=(save_cfg['text_width'], 
                                    save_cfg['text_height'] * 1.3))
    # figsize = plt.rcParams.get('figure.figsize')
    # fig, ax = plt.subplots(figsize=(figsize[0], figsize[1] * 2))
    sns.stripplot(y='Task', x='acc_diff', data=results_df, ax=ax)
    ax.set_xlabel('Accuracy difference')
    ax.set_ylabel('')
    ax.axvline(0, c='k', alpha=0.2)
    plt.tight_layout()

    if save_cfg is not None:
        savename = 'reported_accuracy_diff_scatter'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return ax
//  [python]
def _plot_results_accuracy_diff_scatter(results_df, save_cfg):
    """Plot difference in accuracy for each condition/task as a scatter plot.
    """
    fig, ax = plt.subplots(figsize=(save_cfg['text_width'], 
                                    save_cfg['text_height'] * 1.3))
    # figsize = plt.rcParams.get('figure.figsize')
    # fig, ax = plt.subplots(figsize=(figsize[0], figsize[1] * 2))
    sns.catplot(y='Task', x='acc_diff', data=results_df, ax=ax)
    ax.set_xlabel('Accuracy difference')
    ax.set_ylabel('')
    ax.axvline(0, c='k', alpha=0.2)
    plt.tight_layout()

    if save_cfg is not None:
        savename = 'reported_accuracy_diff_scatter'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return ax
//  [python]
def resource_real_plot2(df, typ):
	ax, tool_order, col_list = prepare_for_simul(4)
	x = tool_order
	
	#ax = sns.barplot(x = 'Tool', y = typ, hue = 'dataset', alpha=1.0, data=df, order=tool_order)
	ax = sns.factorplot(x = 'Tool', y = typ, hue = 'dataset', col='cell line', alpha=1.0, data=df, order=tool_order, kind='bar', legend=True, sharey=False)
	
	if typ == 'time':
		ax.set(ylabel='Time (min)')
	else:
		ax.set(ylabel='Memory usage (GB)')

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

	#matplotlib.pyplot.sca(ax)
	for i in range(2):
		xlabels = ax.axes[0,i].get_xticklabels()
		ax.axes[0,i].set_xticklabels(xlabels, rotation=90)
		ax.axes[0,i].get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
		ax.axes[0,i].grid(b=True, which='major', color='gray', linewidth=1.0)
		ax.axes[0,i].grid(b=True, which='minor', color='gray', linewidth=0.5)
		ax.axes[0,i].xaxis.grid(False)


	ax.set(xlabel='Methods')

	#if sample == 'hela' and t == 'mem':
	#	ax.fig.get_axes()[0].legend(loc='lower left', bbox_to_anchor=(1,0.5), title='dataset')

	plt.savefig('{}_combined.pdf'.format(typ), bbox_inches='tight')
//  [python]
def resource_real_plot2(df, typ):
	ax, tool_order, col_list = prepare_for_simul(4)
	x = tool_order
	
	#ax = sns.barplot(x = 'Tool', y = typ, hue = 'dataset', alpha=1.0, data=df, order=tool_order)
	ax = sns.catplot(x = 'Tool', y = typ, hue = 'dataset', col='cell line', alpha=1.0, data=df, order=tool_order, kind='bar', legend=True, sharey=False)
	
	if typ == 'time':
		ax.set(ylabel='Time (min)')
	else:
		ax.set(ylabel='Memory usage (GB)')

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

	#matplotlib.pyplot.sca(ax)
	for i in range(2):
		xlabels = ax.axes[0,i].get_xticklabels()
		ax.axes[0,i].set_xticklabels(xlabels, rotation=90)
		ax.axes[0,i].get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
		ax.axes[0,i].grid(b=True, which='major', color='gray', linewidth=1.0)
		ax.axes[0,i].grid(b=True, which='minor', color='gray', linewidth=0.5)
		ax.axes[0,i].xaxis.grid(False)


	ax.set(xlabel='Methods')

	#if sample == 'hela' and t == 'mem':
	#	ax.fig.get_axes()[0].legend(loc='lower left', bbox_to_anchor=(1,0.5), title='dataset')

	plt.savefig('{}_combined.pdf'.format(typ), bbox_inches='tight')
//  [python]
def performance_barchart():
    ax = sns.factorplot(x="Injection site", y="Percentage", hue="Treatment", data=df,
                     kind="bar", col="Test day")
    ax.set_ylabels('% place strategy')
    plt.savefig(op.join(figure_location, 'pm_barchart.pdf'), format='pdf')
    return ax
//  [python]
def performance_barchart():
    ax = sns.catplot(x="Injection site", y="Percentage", hue="Treatment", data=df,
                     kind="bar", col="Test day")
    ax.set_ylabels('% place strategy')
    plt.savefig(op.join(figure_location, 'pm_barchart.pdf'), format='pdf')
    return ax
//  [python]
def _plot_results_per_citation_task(results_df, save_cfg):
    """Plot scatter plot of accuracy for each condition and task.
    """
    fig, ax = plt.subplots(figsize=(save_cfg['text_width'], 
                                    save_cfg['text_height'] * 1.3))
    # figsize = plt.rcParams.get('figure.figsize')
    # fig, ax = plt.subplots(figsize=(figsize[0], figsize[1] * 4))
    # Need to make the graph taller otherwise the y axis labels are on top of
    # each other.
    sns.stripplot(y='citation_task', x='Result', hue='model_type', data=results_df, ax=ax, jitter=True)
    sns.boxplot(y='citation_task', x='Result', hue='model_type', data=results_df, ax=ax, boxprops=dict(alpha=0.5))
    ax.set_xlabel('accuracy')
    ax.set_ylabel('')
    plt.tight_layout()

    if save_cfg is not None:
        savename = 'reported_results'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return ax
//  [python]
def _plot_results_per_citation_task(results_df, save_cfg):
    """Plot scatter plot of accuracy for each condition and task.
    """
    fig, ax = plt.subplots(figsize=(save_cfg['text_width'], 
                                    save_cfg['text_height'] * 1.3))
    # figsize = plt.rcParams.get('figure.figsize')
    # fig, ax = plt.subplots(figsize=(figsize[0], figsize[1] * 4))
    # Need to make the graph taller otherwise the y axis labels are on top of
    # each other.
    sns.catplot(y='citation_task', x='Result', hue='model_type', data=results_df, 
                ax=ax)
    ax.set_xlabel('accuracy')
    ax.set_ylabel('')
    plt.tight_layout()

    if save_cfg is not None:
        savename = 'reported_results'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return ax
//  [python]
def resource_real_plot(df_list):
	ax, tool_order, col_list = prepare_for_simul(2)

	#fig, axes = plt.subplots(nrows=1, ncols=4, sharex=True, squeeze=False, figsize=(10,5))
	fig, axes = plt.subplots(1, 4)

	res_type = [ 'time', 'mem', 'time', 'mem' ]

	for t, df, ax_ind in zip(res_type, df_list, range(len(res_type))):
		#ax, tool_order, col_list = prepare_for_simul(4)
		x = tool_order
		
		ax = sns.barplot(x = 'Tool', y = t, hue = 'dataset', data=df, order=tool_order, ax=axes[ax_ind])
		
		#ax = axes[ax_ind]


		#if t == 'time':
		#	ax.set(ylabel='Time (min)')
		#else:
		#	ax.set(ylabel='Memory usage (GB)')

		#sns.despine(left=True, right=True, top=True)

		##matplotlib.pyplot.sca(ax)
		#plt.xticks(rotation=90)

		##axes[0, 0].axes[0,0].get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
		##ax.axes[0, 0].get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
		##plt.grid(b=True, which='major', color='gray', linewidth=1.0)
		##plt.grid(b=True, which='minor', color='gray', linewidth=0.5)
		##plt.gca().xaxis.grid(False)
		#
		#ax.set(xlabel='Methods')

		##if sample == 'hela' and t == 'mem':
		##	ax.fig.get_axes()[0].legend(loc='lower left', bbox_to_anchor=(1,0.5), title='dataset')

		##plt.savefig('{}_{}_combined.pdf'.format(sample, t), bbox_inches='tight')
		
	plt.savefig('real_time_mem.pdf', bbox_inches='tight')
//  [python]
def resource_real_plot(df_list):
	ax, tool_order, col_list = prepare_for_simul(2)

	#fig, axes = plt.subplots(nrows=1, ncols=4, sharex=True, squeeze=False, figsize=(10,5))
	fig, axes = plt.subplots(1, 4)

	res_type = [ 'time', 'mem', 'time', 'mem' ]

	for t, df, ax_ind in zip(res_type, df_list, range(len(res_type))):
		#ax, tool_order, col_list = prepare_for_simul(4)
		x = tool_order
		
		ax = sns.catplot(x = 'Tool', y = t, hue = 'dataset', alpha=1.0, data=df, order=tool_order, kind='bar', legend=False, ax=axes[ax_ind])
		
		#ax = axes[ax_ind]


		#if t == 'time':
		#	ax.set(ylabel='Time (min)')
		#else:
		#	ax.set(ylabel='Memory usage (GB)')

		#sns.despine(left=True, right=True, top=True)

		##matplotlib.pyplot.sca(ax)
		#plt.xticks(rotation=90)

		##axes[0, 0].axes[0,0].get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
		##ax.axes[0, 0].get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
		##plt.grid(b=True, which='major', color='gray', linewidth=1.0)
		##plt.grid(b=True, which='minor', color='gray', linewidth=0.5)
		##plt.gca().xaxis.grid(False)
		#
		#ax.set(xlabel='Methods')

		##if sample == 'hela' and t == 'mem':
		##	ax.fig.get_axes()[0].legend(loc='lower left', bbox_to_anchor=(1,0.5), title='dataset')

		##plt.savefig('{}_{}_combined.pdf'.format(sample, t), bbox_inches='tight')
		
	plt.savefig('real_time_mem.pdf', bbox_inches='tight')
//  [python]
def draw_bar_plot():
    # Copy and modify data for monthly bar plot
    df_bar = (
        df.copy()
        .groupby(pd.Grouper(freq="M"))
        .mean()
        .rename(columns={"value": "avg"})
    )

    df_bar["year"] = pd.DatetimeIndex(df_bar.index).year
    df_bar["month"] = pd.DatetimeIndex(df_bar.index).strftime("%B")

    # Convert data to long form
    df_bar = pd.melt(
        df_bar,
        id_vars=["year", "month"],
        value_vars=["avg"],
    )

    sns.set_theme(style="ticks")

    # Draw the chart
    fig = sns.factorplot(
        data=df_bar,
        x="year",
        y="value",
        hue="month",
        kind="bar",
        legend=False,
    )

    # Config legend, axes and title
    fig.set_xlabels("Years")
    fig.set_ylabels("Average Page Views")
    plt.legend(
        title="Months",
        loc="upper left",
        labels=[
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December",
        ],
    )
    return fig.fig
//  [python]
def draw_bar_plot():
    # Copy and modify data for monthly bar plot
    df_bar = (
        df.copy()
        .groupby(pd.Grouper(freq="M"))
        .mean()
        .rename(columns={"value": "avg"})
    )

    df_bar["year"] = pd.DatetimeIndex(df_bar.index).year
    df_bar["month"] = pd.DatetimeIndex(df_bar.index).strftime("%B")

    # Convert data to long form
    df_bar = pd.melt(
        df_bar,
        id_vars=["year", "month"],
        value_vars=["avg"],
    )

    sns.set_theme(style="ticks")

    # Draw the chart
    fig = sns.catplot(
        data=df_bar,
        x="year",
        y="value",
        hue="month",
        kind="bar",
        legend=False,
    )

    # Config legend, axes and title
    fig.set_xlabels("Years")
    fig.set_ylabels("Average Page Views")
    plt.legend(
        title="Months",
        loc="upper left",
        labels=[
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December",
        ],
    )
    return fig.fig
//  [python]
def _plot_results_accuracy_per_domain(results_df, diff_df, save_cfg):
    """Make scatterplot + boxplot to show accuracy difference by domain.
    """
    fig, axes = plt.subplots(
        nrows=2, ncols=1, sharex=True, 
        figsize=(save_cfg['text_width'], save_cfg['text_height'] / 3), 
        gridspec_kw = {'height_ratios':[5, 1]})

    results_df['Main domain'] = results_df['Main domain'].apply(
        ut.wrap_text, max_char=20)

    sns.stripplot(y='Main domain', x='acc_diff', s=3, jitter=True, 
                data=results_df, ax=axes[0])
    axes[0].set_xlabel('')
    axes[0].set_ylabel('')
    axes[0].axvline(0, c='k', alpha=0.2)

    sns.boxplot(x='acc_diff', data=diff_df, ax=axes[1])
    sns.swarmplot(x='acc_diff', data=diff_df, color="0", size=2, ax=axes[1])
    axes[1].axvline(0, c='k', alpha=0.2)
    axes[1].set_xlabel('Accuracy difference')

    fig.subplots_adjust(wspace=0, hspace=0.02)
    plt.tight_layout()

    logger.info('Number of studies included in the accuracy improvement analysis: {}'.format(
        results_df.shape[0]))
    median = diff_df['acc_diff'].median()
    iqr = diff_df['acc_diff'].quantile(.75) - diff_df['acc_diff'].quantile(.25)
    logger.info('Median gain in accuracy: {:.6f}'.format(median))
    logger.info('Interquartile range of the gain in accuracy: {:.6f}'.format(iqr))
    best_improvement = diff_df.nlargest(3, 'acc_diff')
    logger.info('Best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[0], 
        best_improvement['Citation'].values[0]))
    logger.info('Second best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[1], 
        best_improvement['Citation'].values[1]))
    logger.info('Third best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[2], 
        best_improvement['Citation'].values[2]))

    if save_cfg is not None:
        savename = 'reported_accuracy_per_domain'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return axes
//  [python]
def _plot_results_accuracy_per_domain(results_df, diff_df, save_cfg):
    """Make scatterplot + boxplot to show accuracy difference by domain.
    """
    fig, axes = plt.subplots(
        nrows=2, ncols=1, sharex=True, 
        figsize=(save_cfg['text_width'], save_cfg['text_height'] / 3), 
        gridspec_kw = {'height_ratios':[5, 1]})

    results_df['Main domain'] = results_df['Main domain'].apply(
        ut.wrap_text, max_char=20)

    sns.catplot(y='Main domain', x='acc_diff', s=3, jitter=True, 
                data=results_df, ax=axes[0])
    axes[0].set_xlabel('')
    axes[0].set_ylabel('')
    axes[0].axvline(0, c='k', alpha=0.2)

    sns.boxplot(x='acc_diff', data=diff_df, ax=axes[1])
    sns.swarmplot(x='acc_diff', data=diff_df, color="0", size=2, ax=axes[1])
    axes[1].axvline(0, c='k', alpha=0.2)
    axes[1].set_xlabel('Accuracy difference')

    fig.subplots_adjust(wspace=0, hspace=0.02)
    plt.tight_layout()

    logger.info('Number of studies included in the accuracy improvement analysis: {}'.format(
        results_df.shape[0]))
    median = diff_df['acc_diff'].median()
    iqr = diff_df['acc_diff'].quantile(.75) - diff_df['acc_diff'].quantile(.25)
    logger.info('Median gain in accuracy: {:.6f}'.format(median))
    logger.info('Interquartile range of the gain in accuracy: {:.6f}'.format(iqr))
    best_improvement = diff_df.nlargest(3, 'acc_diff')
    logger.info('Best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[0], 
        best_improvement['Citation'].values[0]))
    logger.info('Second best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[1], 
        best_improvement['Citation'].values[1]))
    logger.info('Third best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[2], 
        best_improvement['Citation'].values[2]))

    if save_cfg is not None:
        savename = 'reported_accuracy_per_domain'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return axes
//  [python]
def plot_overlap_counts(overlap_counts):
    # convert to df
    overlap_counts = overlap_counts.reset_index(name="counts")
    # add type to term to avoid duplicate terms with different types
    overlap_counts.object_name_x = (
        overlap_counts.object_name_x + " (" + overlap_counts.object_type_x + ")"
    )

    # this just makes it look a bit better
    sns.set(rc={"figure.figsize": (20, 20)})

    g = sns.barplot(
        y="object_name_x",
        x="counts",
        hue="object_type_x",
        data=overlap_counts,
        orient="horizontal",
        palette="muted",
    )
    # add numbers to the bars
    for i, v in enumerate(overlap_counts["counts"]):
        plt.text(v + 1, i + 0.25, str(v))

    g.set(ylabel="Overlapping term", xlabel="Term frequency")
    plt.legend(title="Term Type", loc="lower right")
    # plt.savefig('overlaps.png',dpi=1000)
    return plt
//  [python]
def plot_overlap_counts(overlap_counts):
    # convert to df
    overlap_counts = overlap_counts.reset_index(name="counts")
    # add type to term to avoid duplicate terms with different types
    overlap_counts.object_name_x = (
        overlap_counts.object_name_x + " (" + overlap_counts.object_type_x + ")"
    )

    # this just makes it look a bit better
    sns.set(rc={"figure.figsize": (20, 20)})

    g = sns.catplot(
        y="object_name_x",
        x="counts",
        hue="object_type_x",
        data=overlap_counts,
        height=10,
        kind="bar",
        palette="muted",
        orient="horizontal",
        dodge=False,
        legend=False,
    )
    # add numbers to the bars
    for i, v in enumerate(overlap_counts["counts"]):
        plt.text(v + 1, i + 0.25, str(v))

    g.set(ylabel="Overlapping term", xlabel="Term frequency")
    plt.legend(title="Term Type", loc="lower right")
    # plt.savefig('overlaps.png',dpi=1000)
    return plt
//  [python]
def draw_cat_plot():
    # Create DataFrame for cat plot using `pd.melt` using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'.
    df_cat = df[['active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke', 'cardio']].melt(
        id_vars='cardio'
    )

    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the columns for the catplot to work correctly.
    df_cat = df_cat.groupby(['cardio', 'variable', 'value'])['value'].count().reset_index(name='total')

    # Draw the catplot with 'sns.catplot()'
    fig = sns.factorplot(x="variable", y="total", col="cardio", data=df_cat, hue="value", kind="bar").fig

    # Do not modify the next two lines
    fig.savefig('catplot.png')
    return fig
//  [python]
def draw_cat_plot():
    # Create DataFrame for cat plot using `pd.melt` using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'.
    df_cat = df[['active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke', 'cardio']].melt(
        id_vars='cardio'
    )

    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the columns for the catplot to work correctly.
    df_cat = df_cat.groupby(['cardio', 'variable', 'value'])['value'].count().reset_index(name='total')

    # Draw the catplot with 'sns.catplot()'
    fig = sns.catplot(x="variable", y="total", col="cardio", data=df_cat, hue="value", kind="bar").fig

    # Do not modify the next two lines
    fig.savefig('catplot.png')
    return fig
//  [python]
def catPlot(self,data,column):
        column=column.title()
        LabelDictCol = {'Critic Rating':'critic_rating','Audience Rating':'audience_rating','Budget In Millions':'budget_in_millions','Genre':'genre','Year':'year'}      
        sns.countplot(y=LabelDictCol[column], palette="ch:.25", data=data)
        plt.title('Barplot For {}'.format(column.capitalize()),fontsize=20)
        plt.ylabel('{}'.format(column.capitalize()),fontsize=15)
        plt.xlabel('')
        plt.show()
//  [python]
def catPlot(self,data,column):
        column=column.title()
        LabelDictCol = {'Critic Rating':'critic_rating','Audience Rating':'audience_rating','Budget In Millions':'budget_in_millions','Genre':'genre','Year':'year'}      
        sns.catplot(y=LabelDictCol[column], kind="count", palette="ch:.25", data=data)
        plt.title('Barplot For {}'.format(column.capitalize()),fontsize=20)
        plt.ylabel('{}'.format(column.capitalize()),fontsize=15)
        plt.xlabel('')
        plt.show()
//  [python]
def num_conv_kernel_vs_num_attn(save_path):
    sns.set_theme(
        style="ticks",
        font="Times New Roman",
    )
    df = pd.read_csv('./data/num_conv_kernel_vs_num_attn.csv')
    df = df.melt(id_vars=["# Conv2d Kernels"], var_name="# Attention Groups", value_name="CIFAR-10 Top-1 Acc (%)")

    grid = sns.factorplot(
        data=df,
        kind="bar",
        x="# Conv2d Kernels",
        y="CIFAR-10 Top-1 Acc (%)",
        hue="# Attention Groups",
        size=2.5,
        aspect=16 / 9
    )
    grid.set(ylim=(70, 90))
    sns.move_legend(grid, "lower center", bbox_to_anchor=(.5, 0.75), ncol=4)
    grid.fig.tight_layout(pad=0.2, rect=(0, 0, 1, 0.9))

    if save_path:
        plt.savefig(save_path, format="pdf")
    else:
        plt.show()
//  [python]
def num_conv_kernel_vs_num_attn(save_path):
    sns.set_theme(
        style="ticks",
        font="Times New Roman",
    )
    df = pd.read_csv('./data/num_conv_kernel_vs_num_attn.csv')
    df = df.melt(id_vars=["# Conv2d Kernels"], var_name="# Attention Groups", value_name="CIFAR-10 Top-1 Acc (%)")

    grid = sns.catplot(
        data=df,
        kind="bar",
        x="# Conv2d Kernels",
        y="CIFAR-10 Top-1 Acc (%)",
        hue="# Attention Groups",
        height=2.5,
        aspect=16 / 9
    )
    grid.set(ylim=(70, 90))
    sns.move_legend(grid, "lower center", bbox_to_anchor=(.5, 0.75), ncol=4)
    grid.fig.tight_layout(pad=0.2, rect=(0, 0, 1, 0.9))

    if save_path:
        plt.savefig(save_path, format="pdf")
    else:
        plt.show()
//  [python]
def fix_num_conv_kernel_per_attn(save_path):
    sns.set_theme(
        style="ticks",
        font="Times New Roman",
    )
    df = pd.read_csv('./data/fix_num_conv_kernel_per_attn.csv')
    df = df.melt(id_vars=["# Conv2d Kernels per Attention Group"], var_name="# Attention Groups", value_name="CIFAR-10 Top-1 Acc (%)")

    grid = sns.factorplot(
        data=df,
        kind="bar",
        x="# Conv2d Kernels per Attention Group",
        y="CIFAR-10 Top-1 Acc (%)",
        hue="# Attention Groups",
        size=2.5,
        aspect=16 / 9
    )
    grid.set(ylim=(70, 90))
    sns.move_legend(grid, "lower center", bbox_to_anchor=(.5, 0.75), ncol=4)
    grid.fig.tight_layout(pad=0.2, rect=(0, 0, 1, 0.9))

    if save_path:
        plt.savefig(save_path, format="pdf")
    else:
        plt.show()
//  [python]
def fix_num_conv_kernel_per_attn(save_path):
    sns.set_theme(
        style="ticks",
        font="Times New Roman",
    )
    df = pd.read_csv('./data/fix_num_conv_kernel_per_attn.csv')
    df = df.melt(id_vars=["# Conv2d Kernels per Attention Group"], var_name="# Attention Groups", value_name="CIFAR-10 Top-1 Acc (%)")

    grid = sns.catplot(
        data=df,
        kind="bar",
        x="# Conv2d Kernels per Attention Group",
        y="CIFAR-10 Top-1 Acc (%)",
        hue="# Attention Groups",
        height=2.5,
        aspect=16 / 9
    )
    grid.set(ylim=(70, 90))
    sns.move_legend(grid, "lower center", bbox_to_anchor=(.5, 0.75), ncol=4)
    grid.fig.tight_layout(pad=0.2, rect=(0, 0, 1, 0.9))

    if save_path:
        plt.savefig(save_path, format="pdf")
    else:
        plt.show()
//  [python]
def attn_group_vs_attn_depth(save_path):
    sns.set_theme(
        style="ticks",
        font="Times New Roman",
        palette="Paired"
    )
    df = pd.read_csv('./data/attn_group_vs_attn_depth.csv')
    df = df.melt(id_vars=["# Conv2d Kernels"], var_name="# Attention Groups - Attention Depth", value_name="CIFAR-10 Top-1 Acc (%)")

    grid = sns.factorplot(
        data=df,
        kind="bar",
        x="# Conv2d Kernels",
        y="CIFAR-10 Top-1 Acc (%)",
        hue="# Attention Groups - Attention Depth",
        size=2.5,
        aspect=16 / 9
    )
    grid.set(ylim=(70, 90))
    sns.move_legend(grid, "lower center", bbox_to_anchor=(.5, 0.75), ncol=4)
    grid.fig.tight_layout(pad=0.2, rect=(0, 0, 1, 0.9))

    if save_path:
        plt.savefig(save_path, format="pdf")
    else:
        plt.show()
//  [python]
def attn_group_vs_attn_depth(save_path):
    sns.set_theme(
        style="ticks",
        font="Times New Roman",
        palette="Paired"
    )
    df = pd.read_csv('./data/attn_group_vs_attn_depth.csv')
    df = df.melt(id_vars=["# Conv2d Kernels"], var_name="# Attention Groups - Attention Depth", value_name="CIFAR-10 Top-1 Acc (%)")

    grid = sns.catplot(
        data=df,
        kind="bar",
        x="# Conv2d Kernels",
        y="CIFAR-10 Top-1 Acc (%)",
        hue="# Attention Groups - Attention Depth",
        height=2.5,
        aspect=16 / 9
    )
    grid.set(ylim=(70, 90))
    sns.move_legend(grid, "lower center", bbox_to_anchor=(.5, 0.75), ncol=4)
    grid.fig.tight_layout(pad=0.2, rect=(0, 0, 1, 0.9))

    if save_path:
        plt.savefig(save_path, format="pdf")
    else:
        plt.show()
//  [python]
def conv_depth_vs_attn_depth(save_path):
    sns.set_theme(
        style="ticks",
        font="Times New Roman",
        palette="Paired"
    )
    df = pd.read_csv('./data/conv_depth_vs_attn_depth.csv')
    df = df.melt(id_vars=["# Conv2d Kernels"], var_name="Conv2d Depth - Attention Depth", value_name="CIFAR-10 Top-1 Acc (%)")

    grid = sns.factorplot(
        data=df,
        kind="bar",
        x="# Conv2d Kernels",
        y="CIFAR-10 Top-1 Acc (%)",
        hue="Conv2d Depth - Attention Depth",
        size=2.5,
        aspect=16 / 9
    )
    grid.set(ylim=(68, 93))
    sns.move_legend(grid, "lower center", bbox_to_anchor=(.5, 0.75), ncol=4)
    grid.fig.tight_layout(pad=0.2, rect=(0, 0, 1, 0.9))

    if save_path:
        plt.savefig(save_path, format="pdf")
    else:
        plt.show()
//  [python]
def conv_depth_vs_attn_depth(save_path):
    sns.set_theme(
        style="ticks",
        font="Times New Roman",
        palette="Paired"
    )
    df = pd.read_csv('./data/conv_depth_vs_attn_depth.csv')
    df = df.melt(id_vars=["# Conv2d Kernels"], var_name="Conv2d Depth - Attention Depth", value_name="CIFAR-10 Top-1 Acc (%)")

    grid = sns.catplot(
        data=df,
        kind="bar",
        x="# Conv2d Kernels",
        y="CIFAR-10 Top-1 Acc (%)",
        hue="Conv2d Depth - Attention Depth",
        height=2.5,
        aspect=16 / 9
    )
    grid.set(ylim=(68, 93))
    sns.move_legend(grid, "lower center", bbox_to_anchor=(.5, 0.75), ncol=4)
    grid.fig.tight_layout(pad=0.2, rect=(0, 0, 1, 0.9))

    if save_path:
        plt.savefig(save_path, format="pdf")
    else:
        plt.show()
//  [python]
def draw_cat_plot():
    # Create DataFrame for cat plot using `pd.melt` 
    #using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'.
    df_cat = pd.melt(df,value_vars = ['cholesterol', 'gluc', 'smoke', 'alco', 'active', 'overweight'],id_vars=['cardio'])

    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature.
    #You will have to rename one of the columns for the catplot to work correctly.
    df_cat = pd.DataFrame(df_cat.groupby(['variable', 'value', 'cardio'])['value']
                          .count()).rename(columns={'value': 'total'}).reset_index()    

    # Draw the catplot with 'sns.catplot()'
    fig = plt.figure(figsize=(8,8))
    g = sns.factorplot(data = df_cat, x='variable', y='total', hue='value', col='cardio', kind="bar")
    fig = g.fig

    # Do not modify the next two lines
    fig.savefig('catplot.png')
    return fig
//  [python]
def draw_cat_plot():
    # Create DataFrame for cat plot using `pd.melt` 
    #using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'.
    df_cat = pd.melt(df,value_vars = ['cholesterol', 'gluc', 'smoke', 'alco', 'active', 'overweight'],id_vars=['cardio'])

    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature.
    #You will have to rename one of the columns for the catplot to work correctly.
    df_cat = pd.DataFrame(df_cat.groupby(['variable', 'value', 'cardio'])['value']
                          .count()).rename(columns={'value': 'total'}).reset_index()    

    # Draw the catplot with 'sns.catplot()'
    fig = plt.figure(figsize=(8,8))
    sns.catplot(data = df_cat, x='variable', y='total', hue='value', col='cardio', kind="bar")

    # Do not modify the next two lines
    fig.savefig('catplot.png')
    return fig
//  [python]
def save_cat_plot(filename, y, maintitle, subtitle, df, col):
    print("Creating " + filename)
    g = sns.factorplot(x="Concurrent Users", y=y, hue="Scenario Name", col=col, data=df, kind='point', size=7, col_wrap=2)
    for ax in g.axes.flatten():
        ax.yaxis.set_major_formatter(tkr.FuncFormatter(lambda y_value, p: "{:,}".format(y_value)))
    plt.subplots_adjust(top=0.9)
    g.fig.suptitle(maintitle + "\n" + subtitle)
    g.savefig(filename)
    plt.clf()
    plt.close(g.fig)
//  [python]
def save_cat_plot(filename, y, maintitle, subtitle, df, col):
    print("Creating " + filename)
    g = sns.catplot(x="Concurrent Users", y=y, hue="Scenario Name", col=col, data=df, kind='point', height=7, col_wrap=2)
    for ax in g.axes.flatten():
        ax.yaxis.set_major_formatter(tkr.FuncFormatter(lambda y_value, p: "{:,}".format(y_value)))
    plt.subplots_adjust(top=0.9)
    g.fig.suptitle(maintitle + "\n" + subtitle)
    g.savefig(filename)
    plt.clf()
    plt.close(g.fig)
//  [python]
def barplot_frequency_distributions(df, frequency, cardinality, source):
  """Barplot for comparing multiple frequency distributions.

  Args:
    df: a pd.DataFrame that has the columns of the frequency level, the
      cardinality, and the source, specified by frequency, cardinality, and
      source respectively.
    frequency: a column name in df specifying the per frequency level.
    cardinality: a column name in df specifying the cardinality of the set of
      the corresponding frequency level.
    source: a column name in df specifying the source of the cardinality.
      For example, it could be a column containing labels like
      'estimated_cardinality' and 'true_cardinality'. Different source will
      have different colors in the plot.

  Returns:
    A matplotlib.axes.Axes object of the barplot.
  """
  _, ax = plt.subplots()
  sns.barplot(x=frequency, y=cardinality, hue=source, data=df, palette='muted', ax=ax)
  ax.set(xlabel='Per frequency level', ylabel='Cardinality')
  return ax
//  [python]
def barplot_frequency_distributions(df, frequency, cardinality, source):
  """Barplot for comparing multiple frequency distributions.

  Args:
    df: a pd.DataFrame that has the columns of the frequency level, the
      cardinality, and the source, specified by frequency, cardinality, and
      source respectively.
    frequency: a column name in df specifying the per frequency level.
    cardinality: a column name in df specifying the cardinality of the set of
      the corresponding frequency level.
    source: a column name in df specifying the source of the cardinality.
      For example, it could be a column containing labels like
      'estimated_cardinality' and 'true_cardinality'. Different source will
      have different colors in the plot.

  Returns:
    A matplotlib.axes.Axes object of the barplot.
  """
  _, ax = plt.subplots()
  sns.catplot(x=frequency, y=cardinality, hue=source, data=df,
              kind='bar', palette='muted', ax=ax)
  ax.set(xlabel='Per frequency level', ylabel='Cardinality')
  return ax