jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def draw_stateless(df2, resource):
    df = df2[df2["Resource"] == resource]
    avgs = df.groupby(['Limit','Mult']).mean().reset_index()
    print (avgs)
    avgs["Benchmark"] = "Mean"
    df = pd.concat([df,avgs], axis=0, ignore_index=True, sort=False)

    set_style()
    ax = sns.catplot(x="Benchmark", y="Execution Time Improvement", hue="Limit", col="Mult", data=df, kind="bar", 
                    palette=("Purples"),  height=6, aspect=0.9, legend=False)
    ax.set_xticklabels(rotation=90)
    ax.fig.tight_layout()
    plt.legend(loc=("upper center"),
            bbox_to_anchor=(-.5, 1.49),
            ncol=5,
            prop={'size': 20},
            title="Adaptation Limit",
    
    )
    ax.axes.flatten()[0].set_ylim(df["Execution Time Improvement"].min()-0.02, df["Execution Time Improvement"].max()+0.02)
    ax.axes.flatten()[0].set_ylabel('Speedup \nover Shared', fontsize = 20)

    axes = ax.axes.flatten()
    for ax in axes:
        ax.set_xlabel("")
        for i, bar in enumerate(ax.patches):
            bar.set_edgecolor('black')

    plt.savefig("fig-adaptive-{}.pdf".format(resource), bbox_inches='tight')
//  [python]
sns.set(font_scale=1.1, rc={'text.usetex' : True})

df = pd.read_csv("sdr.csv", delimiter=",")

g = sns.factorplot("Songs", "Mean SDR", hue="Model", col="Source", data=df, kind="bar", size=3, aspect=2, sharey=False)
//  [python]
sns.set(font_scale=1.1, rc={'text.usetex' : True})

df = pd.read_csv("sdr.csv", delimiter=",")

g = sns.catplot("Songs", "Mean SDR", hue="Model", col="Source", data=df, kind="bar", height=3, aspect=2, sharey=False)
//  [python]
m.render('shenghuiHM.html')


mr = a[a.ranks<=3]
mr.ranks = mr.ranks.astype(int)
plt.figure(figsize=[6,8])
for rank in mr.ranks.unique():
    subset = mr[mr.ranks == rank]
    g = sns.factorplot(x='number', y='city', hue='capital', data=subset, kind='bar', orient='h', sharey=False)
    g.fig.suptitle(f'Rank: {rank}')
    plt.show()
//  [python]
m.render('shenghuiHM.html')


mr = a[a.ranks<=3]
mr.ranks = mr.ranks.astype(int)
plt.figure(figsize=[6,8])
sns.catplot(x='number',y='city', hue='capital', data=mr, row='ranks', kind='bar', orient='h', sharey=False)
//  [python]
def make_2way_boxplot(
    *,
    df,
    target_header,
    y,
    hue,
    slice_dir,
    dataset,
    aspect,
    name: Optional[str] = None,
    make_pngs: bool = True,
    make_pdfs: bool = True,
) -> None:
    sns.set(style='whitegrid')
    g = sns.factorplot(
        x=target_header,
        y=y,
        hue=hue,
        data=df,
        kind='box',
        legend_out=False,
        aspect=aspect,
    )
    g.set(xlim=[0, 1.0], ylabel='')
    _clean_legend_title(g._legend)
    plt.tight_layout()

    if name is None:
        name = f'{dataset}_loss_{hue}'
    if make_pngs:
        plt.savefig(os.path.join(slice_dir, f'{name}.png'.lower()), dpi=300)
    if make_pdfs:
        plt.savefig(os.path.join(slice_dir, f'{name}.pdf'.lower()))
    plt.close(plt.gcf())
//  [python]
def make_2way_boxplot(
    *,
    df,
    target_header,
    y,
    hue,
    slice_dir,
    dataset,
    aspect,
    name: Optional[str] = None,
    make_pngs: bool = True,
    make_pdfs: bool = True,
) -> None:
    sns.set(style='whitegrid')
    g = sns.catplot(
        x=target_header,
        y=y,
        hue=hue,
        data=df,
        kind='box',
        legend_out=False,
        aspect=aspect,
    )
    g.set(xlim=[0, 1.0], ylabel='')
    _clean_legend_title(g._legend)
    plt.tight_layout()

    if name is None:
        name = f'{dataset}_loss_{hue}'
    if make_pngs:
        plt.savefig(os.path.join(slice_dir, f'{name}.png'.lower()), dpi=300)
    if make_pdfs:
        plt.savefig(os.path.join(slice_dir, f'{name}.pdf'.lower()))
    plt.close(plt.gcf())
//  [python]
def plot_3d_barplot(
    *,
    df, y, col, hue, dataset, optimizer, target_header, slice_dir,
    name: Optional[str] = None,
    make_pngs: bool = True,
    make_pdfs: bool = True,
) -> None:
    g = sns.factorplot(
        kind='bar',
        estimator=np.median,
        data=df,
        x=target_header,
        y=y,
        height=6,
        hue=hue,
        col=col,
        col_wrap=4,
        legend=True,
        legend_out=False,
        ci=None,
    )
    g.set_titles(template='{col_name}')
    g.set_ylabels('')
    g.set(xlim=[0.0, 1.0])
    _clean_legend_title(g._legend)
    plt.tight_layout()
    if name is None:
        name = f'{dataset}_{optimizer}_{y}_{col}_{hue}'
    if make_pngs:
        g.savefig(os.path.join(slice_dir, f'{name}.png'.lower()), dpi=300)
    if make_pdfs:
        g.savefig(os.path.join(slice_dir, f'{name}.pdf'.lower()))
    plt.close(g.fig)
//  [python]
def plot_3d_barplot(
    *,
    df, y, col, hue, dataset, optimizer, target_header, slice_dir,
    name: Optional[str] = None,
    make_pngs: bool = True,
    make_pdfs: bool = True,
) -> None:
    g = sns.catplot(
        kind='bar',
        estimator=np.median,
        data=df,
        x=target_header,
        y=y,
        height=6,
        hue=hue,
        col=col,
        col_wrap=4,
        legend=True,
        legend_out=False,
        ci=None,
    )
    g.set_titles(template='{col_name}')
    g.set_ylabels('')
    g.set(xlim=[0.0, 1.0])
    _clean_legend_title(g._legend)
    plt.tight_layout()
    if name is None:
        name = f'{dataset}_{optimizer}_{y}_{col}_{hue}'
    if make_pngs:
        g.savefig(os.path.join(slice_dir, f'{name}.png'.lower()), dpi=300)
    if make_pdfs:
        g.savefig(os.path.join(slice_dir, f'{name}.pdf'.lower()))
    plt.close(g.fig)
//  [python]
def case_day_country (Date, df):
    df = df.groupby(['Country/Region', 'Date'], as_index = False)['ConfirmedCases'].sum()
    date_filter = (df['Date'] == Date)
    df = df.loc[date_filter]
    df.sort_values('ConfirmedCases', ascending = False, inplace = True)
    sns.barplot(x = 'Country/Region', y = 'ConfirmedCases' , data = df.head(10))
//  [python]
def case_day_country (Date, df):
    df = df.groupby(['Country/Region', 'Date'], as_index = False)['ConfirmedCases'].sum()
    date_filter = (df['Date'] == Date)
    df = df.loc[date_filter]
    df.sort_values('ConfirmedCases', ascending = False, inplace = True)
    sns.catplot(x = 'Country/Region', y = 'ConfirmedCases' , data = df.head(10), height=5,aspect=3, kind = 'bar')
//  [python]
def main():
    save_img_dir='./data/histograms_idrid_plots/separability_consistency'
    os.makedirs(save_img_dir, exist_ok=True)
    fps = glob.glob('./data/histograms_idrid_data/IDRiD*.npz')
    metadatas = [PATTERN.search(fp).groupdict() for fp in fps]

    meta = pd.DataFrame(metadatas)

    for healthy_or_diseased in ['healthy', 'diseased']:
        # bar plot of standard deviation of avg histogram, one subplot per
        # channel, each containing many models
        df = get_consistency_scores(fps, meta).xs(healthy_or_diseased)
        df['std_as_pct'] = df.groupby(['channel', 'lesion_name'])['std'].transform(lambda x: x/x.max())
        fig = sns.factorplot(x='lesion_name', y='std', hue='method_name', col='channel', data=df.reset_index(), kind='bar')
        fig.set_titles("%s {col_name} {col_var}" % (healthy_or_diseased))
        fig.savefig(join(save_img_dir, f'std_hists_{healthy_or_diseased}.png'))

        # show the histograms for each lesion, method, channel, and
        # averaged over whole dataset.  do it for all healthy and diseased imgs
        hists = get_hists(fps, meta, healthy_or_diseased)
        for lesion in ['MA', 'HE', 'EX', 'SE']:
            fig = sns.factorplot(x='pixel_intensity', y='hist', hue='method_name', col='channel', data=hists.query(f'lesion_name=="{lesion}"').query('pixel_intensity > 0 and pixel_intensity < 256'))
            fig.set_titles("%s %s {col_name} {col_var}" % (healthy_or_diseased, lesion))
            fig.set_xticklabels([])
            fig.savefig(join(save_img_dir, f'avg_hists_{healthy_or_diseased}_{lesion}.png'))

    globals().update(locals())
//  [python]
def main():
    save_img_dir='./data/histograms_idrid_plots/separability_consistency'
    os.makedirs(save_img_dir, exist_ok=True)
    fps = glob.glob('./data/histograms_idrid_data/IDRiD*.npz')
    metadatas = [PATTERN.search(fp).groupdict() for fp in fps]

    meta = pd.DataFrame(metadatas)

    for healthy_or_diseased in ['healthy', 'diseased']:
        # bar plot of standard deviation of avg histogram, one subplot per
        # channel, each containing many models
        df = get_consistency_scores(fps, meta).xs(healthy_or_diseased)
        df['std_as_pct'] = df.groupby(['channel', 'lesion_name'])['std'].transform(lambda x: x/x.max())
        fig = sns.catplot(x='lesion_name', y='std', hue='method_name', col='channel', data=df.reset_index(), kind='bar')
        fig.set_titles("%s {col_name} {col_var}" % (healthy_or_diseased))
        fig.savefig(join(save_img_dir, f'std_hists_{healthy_or_diseased}.png'))

        # show the histograms for each lesion, method, channel, and
        # averaged over whole dataset.  do it for all healthy and diseased imgs
        hists = get_hists(fps, meta, healthy_or_diseased)
        for lesion in ['MA', 'HE', 'EX', 'SE']:
            fig = sns.catplot(x='pixel_intensity', y='hist', hue='method_name', col='channel', data=hists.query(f'lesion_name=="{lesion}"').query('pixel_intensity > 0 and pixel_intensity < 256'))
            fig.set_titles("%s %s {col_name} {col_var}" % (healthy_or_diseased, lesion))
            fig.set_xticklabels([])
            fig.savefig(join(save_img_dir, f'avg_hists_{healthy_or_diseased}_{lesion}.png'))

    globals().update(locals())
//  [python]
sns.set_theme(style="whitegrid")

penguins = sns.load_dataset("penguins")

# Draw a nested barplot by species and sex
g = sns.barplot(
    data=penguins,
    x="species", y="body_mass_g", hue="sex",
    errorbar="sd", palette="dark", alpha=.6
)
//  [python]
sns.set_theme(style="whitegrid")

penguins = sns.load_dataset("penguins")

# Draw a nested barplot by species and sex
g = sns.catplot(
    data=penguins, kind="bar",
    x="species", y="body_mass_g", hue="sex",
    errorbar="sd", palette="dark", alpha=.6, height=6
)
//  [python]
def make_loss_plot_barplot(
    *,
    df: pd.DataFrame,
    target_header: str,
    hue: str,
    output_directory: str,
    dataset: str,
    name: Optional[str] = None,
    make_pngs: bool = True,
    make_pdfs: bool = True,
) -> None:
    sns.set(font_scale=1.5, style='whitegrid')

    dfs = [
        sdf
        for _, sdf in df.groupby(['model', 'loss'])
        if sdf[hue].nunique() == 2
    ]
    if not dfs:
        logger.warning('Could not make model/loss barplot for %s', hue)
        g = sns.factorplot(
            kind='bar',
            estimator=np.median,
            data=df,
            x=target_header,
            y='model',
            height=6,
            col='loss',
            col_wrap=2,
            legend=True,
            legend_out=False,
            ci=None,
        )
        if name is None:
            name = f'{dataset}_model_loss'

    else:
        plot_df = pd.concat(dfs)
        g = sns.factorplot(
            kind='bar',
            estimator=np.median,
            data=plot_df,
            x=target_header,
            y='model',
            height=6,
            hue=hue,
            col='loss',
            col_wrap=2,
            legend=True,
            legend_out=False,
            ci=None,
        )
        _clean_legend_title(g._legend)
        if name is None:
            name = f'{dataset}_model_loss_{hue}'

    g.set_titles(template='{col_name}')
    g.set_ylabels('')
    g.set(xlim=[0.0, 1.0])
    plt.tight_layout()

    if make_pngs:
        g.savefig(os.path.join(output_directory, f'{name}.png'.lower()), dpi=300)
    if make_pdfs:
        g.savefig(os.path.join(output_directory, f'{name}.pdf'.lower()))
    plt.close(g.fig)
//  [python]
def make_loss_plot_barplot(
    *,
    df: pd.DataFrame,
    target_header: str,
    hue: str,
    output_directory: str,
    dataset: str,
    name: Optional[str] = None,
    make_pngs: bool = True,
    make_pdfs: bool = True,
) -> None:
    sns.set(font_scale=1.5, style='whitegrid')

    dfs = [
        sdf
        for _, sdf in df.groupby(['model', 'loss'])
        if sdf[hue].nunique() == 2
    ]
    if not dfs:
        logger.warning('Could not make model/loss barplot for %s', hue)
        g = sns.catplot(
            kind='bar',
            estimator=np.median,
            data=df,
            x=target_header,
            y='model',
            height=6,
            col='loss',
            col_wrap=2,
            legend=True,
            legend_out=False,
            ci=None,
        )
        if name is None:
            name = f'{dataset}_model_loss'

    else:
        plot_df = pd.concat(dfs)
        g = sns.catplot(
            kind='bar',
            estimator=np.median,
            data=plot_df,
            x=target_header,
            y='model',
            height=6,
            hue=hue,
            col='loss',
            col_wrap=2,
            legend=True,
            legend_out=False,
            ci=None,
        )
        _clean_legend_title(g._legend)
        if name is None:
            name = f'{dataset}_model_loss_{hue}'

    g.set_titles(template='{col_name}')
    g.set_ylabels('')
    g.set(xlim=[0.0, 1.0])
    plt.tight_layout()

    if make_pngs:
        g.savefig(os.path.join(output_directory, f'{name}.png'.lower()), dpi=300)
    if make_pdfs:
        g.savefig(os.path.join(output_directory, f'{name}.pdf'.lower()))
    plt.close(g.fig)
//  [python]
def plot_explained_variance(self, datamodels_map, num_components=None):
        exp_vars = self.get_explained_variance(datamodels_map)
        df = pd.DataFrame(exp_vars).reset_index().melt(id_vars='index')
        df.columns = ['index', 'datamodel', 'explained_variance']
        num_components = num_components if num_components else max(df['index'])
        fg = sns.factorplot(x='index', y='explained_variance', hue='datamodel', kind='bar', data=df[df['index']<num_components])
        return fg
//  [python]
def plot_explained_variance(self, datamodels_map, num_components=None):
        exp_vars = self.get_explained_variance(datamodels_map)
        df = pd.DataFrame(exp_vars).reset_index().melt(id_vars='index')
        df.columns = ['index', 'datamodel', 'explained_variance']
        num_components = num_components if num_components else max(df['index'])
        fg = sns.catplot(x='index', y='explained_variance', hue='datamodel', kind='bar', data=df[df['index']<num_components])
        return fg
//  [python]
def plot_simple_comparison(df,x,hue,y='Percent Replicating',order=None,hue_order=None,
col=None, col_order=None, col_wrap=None,row=None,row_order=None,jitter=0.25,dodge=True,plotname=None,
ylim=None, title=None,aspect=1,sharex=True,facet_kws={}):
    plt.rcParams["legend.markerscale"] =1.5
    sns.set_style("ticks")
    sns.set_context("paper",font_scale=1.5)
    g = sns.FacetGrid(data=df, col=col, col_order = col_order, col_wrap=col_wrap,row=row,
    row_order = row_order, sharex=sharex, aspect=aspect, **facet_kws)
    g.map(sns.pointplot, x, y, order=order, hue=hue, hue_order=hue_order, palette='Set1',
    jitter=jitter, dodge=dodge, s=80,linewidth=1, alpha=0.8)
    if sharex:
        labels = []
        if not order:
            orig_labels = list(dict.fromkeys(df[x].values).keys())
        else:
            orig_labels = order
        for label in orig_labels:
            if type(label)!= str:
                label = str(int(label))
            labels.append(textwrap.fill(label, width=45/len(orig_labels),break_long_words=False))
        g.set_xticklabels(labels=labels,rotation=0)
    if ylim:
        ymin,ymax=ylim
    else:
        ymin = 50
        ymax = 80 
    if df[y].min()<ymin:
        ymin = df[y].min()-2
    if df[y].max()>ymax:
        ymax = df[y].max()+2
    g.set(ylim=([ymin,ymax]))    
    if plotname:
        plotname = f"../figures/{plotname}"
    else:
        plotname = f"../figures/{x}-{y}-{hue}-{col}-{row}.svg"
    if not col:
        if not row:
            if title:
                g.set(title=title)
            else:
                g.set(title=f"{x}-{y}")
    g.savefig(plotname,dpi=300)
    print(f'Saved to {plotname}')
//  [python]
def plot_simple_comparison(df,x,hue,y='Percent Replicating',order=None,hue_order=None,
col=None, col_order=None, col_wrap=None,row=None,row_order=None,jitter=0.25,dodge=True,plotname=None,
ylim=None, title=None,aspect=1,sharex=True,facet_kws={}):
    plt.rcParams["legend.markerscale"] =1.5
    sns.set_style("ticks")
    sns.set_context("paper",font_scale=1.5)
    g = sns.catplot(data=df, x = x ,y = y, order=order,
    hue=hue, hue_order=hue_order, col=col, col_order = col_order, col_wrap=col_wrap,row=row,
    row_order = row_order, palette='Set1',s=80,linewidth=1,jitter=jitter,
    alpha=0.8,dodge=dodge,aspect=aspect,sharex=sharex,facet_kws=facet_kws)
    if sharex:
        labels = []
        if not order:
            orig_labels = list(dict.fromkeys(df[x].values).keys())
        else:
            orig_labels = order
        for label in orig_labels:
            if type(label)!= str:
                label = str(int(label))
            labels.append(textwrap.fill(label, width=45/len(orig_labels),break_long_words=False))
        g.set_xticklabels(labels=labels,rotation=0)
    if ylim:
        ymin,ymax=ylim
    else:
        ymin = 50
        ymax = 80 
    if df[y].min()<ymin:
        ymin = df[y].min()-2
    if df[y].max()>ymax:
        ymax = df[y].max()+2
    g.set(ylim=([ymin,ymax]))    
    if plotname:
        plotname = f"../figures/{plotname}"
    else:
        plotname = f"../figures/{x}-{y}-{hue}-{col}-{row}.svg"
    if not col:
        if not row:
            if title:
                g.set(title=title)
            else:
                g.set(title=f"{x}-{y}")
    g.savefig(plotname,dpi=300)
    print(f'Saved to {plotname}')
//  [python]
def plot_lags_box(data, x, y, hue=None, style=None, col=None, palette=COLOR_PALETTE, **kwa_kind):
	"""Plot a seaborn grid of boxplots to show the lags."""
	plt.figure()
	fig = sns.factorplot(
			x=x, y=y, hue=hue, col=col, data=data, palette=palette, #style=style,
			legend=False, legend_out=False,
			flierprops=dict(marker="o"),
			kind="box"
		).set_titles("{col_name}").add_legend(title="")
	return fig
//  [python]
def plot_lags_box(data, x, y, hue=None, style=None, col=None, palette=COLOR_PALETTE, **kwa_kind):
	"""Plot a seaborn grid of boxplots to show the lags."""
	plt.figure()
	fig = sns.catplot(
			x=x, y=y, hue=hue, col=col, data=data, palette=palette, #style=style,
			legend=False, legend_out=False,
			flierprops=dict(marker="o"),
			kind="box"
		).set_titles("{col_name}").add_legend(title="")
	return fig
//  [python]
cols = ["tool", "vers", "test", "jobs", "conf", "file", "start", "end size", "time"]
data = pd.read_csv("data.csv", names=cols)
sns.set_theme()
plot = sns.barplot(data=data, x="tool", y="end size")
//  [python]
cols = ["tool", "vers", "test", "jobs", "conf", "file", "start", "end size", "time"]
data = pd.read_csv("data.csv", names=cols)
sns.set_theme()
plot = sns.catplot(data=data, kind="bar", x="tool", y="end size")
//  [python]
def plot_metric_results_cat(data, x, y, hue=None, style=None, col=None, palette=COLOR_PALETTE, **kwa_kind):
	"""Plot a seaborn grid of barplots to show the metric results."""
	g = sns.factorplot(
			x=x, y=y, hue=hue, col=col, data=data, palette=palette, #style=style,
			legend=False, legend_out=False,
			capsize=0.1, kind="bar"
		).set_titles("{col_name}").add_legend(title="")
	g.set(ylim=(0, 1))
	return g
//  [python]
def plot_metric_results_cat(data, x, y, hue=None, style=None, col=None, palette=COLOR_PALETTE, **kwa_kind):
	"""Plot a seaborn grid of barplots to show the metric results."""
	fig = sns.catplot(
			x=x, y=y, hue=hue, col=col, data=data, palette=palette, #style=style,
			legend=False, legend_out=False,
			capsize=0.1, kind="bar"
		).set_titles("{col_name}").add_legend(title="")
	fig.set(ylim=(0, 1))
	return fig
//  [python]
g.map_dataframe(sns.lineplot, x="time", y="air_quality", ci=False)
g.set_axis_labels("Time", "Air Quality")
g.set(xlim=(0, 1440), ylim=(0, None))
g.add_legend()


# %% Timeline place per person
sns.factorplot(x="time", y="name", hue="activity", kind="swarm", data=people)
//  [python]
g.map_dataframe(sns.lineplot, x="time", y="air_quality", ci=False)
g.set_axis_labels("Time", "Air Quality")
g.set(xlim=(0, 1440), ylim=(0, None))
g.add_legend()


# %% Timeline place per person
sns.catplot(x="time", y="name", hue="activity", kind="swarm", data=people)
//  [python]
def plot_rank(data, plot_detectors=["CLIP B/16", "Current Method"]):
    benchmarks = ['Hard', 'Medium', 'Easy', 'Trivial']
    attributes = ['Color', 'Material', 'Pattern', 'Transparency']
    sns.set_theme(style="whitegrid", context="talk", font='serif', font_scale=0.8, rc={'text.usetex': False, 'text.latex.preamble': r'\usepackage{underscore}'})

    plot_data = data.query('metric == "Mean Rank" & detector in @plot_detectors').explode('value', ignore_index=True) #.assign(value=lambda x: 1 / x.value)
    palette = matplotlib.colormaps.get_cmap('rainbow')
    palette = [palette(i) for i in np.linspace(0, 1, len(plot_detectors))]
    markers = ['D', 'o', 'X', 's', 'P', 'd']

    g = sns.FacetGrid(data=plot_data, col='benchmark', hue='detector', col_wrap=4, height=2.4, aspect=1.3, palette=palette, sharey=False)
    g.map(sns.pointplot, 'num_negatives', 'value', markers=markers, dodge=0.25, estimator=np.median, join=False, ci=None, scale=0.8, linestyles="")
    g.add_legend(title='Detector')
    g.set_titles(col_template="{col_name}")
    g.set(xlabel=None, ylabel='Rank')
    g.fig.text(0.5, 0.01, r'Number of negative captions $N$', ha='center', va='center')

    for ax in g.axes.flat:
        ax.yaxis.set_major_locator(plt.MultipleLocator(1))
        ax.grid(which='major', axis='x', visible=True)
        ax.invert_yaxis()

    g.fig.tight_layout()
//  [python]
def plot_rank(data, plot_detectors=["CLIP B/16", "Current Method"]):
    benchmarks = ['Hard', 'Medium', 'Easy', 'Trivial']
    attributes = ['Color', 'Material', 'Pattern', 'Transparency']
    sns.set_theme(style="whitegrid", context="talk", font='serif', font_scale=0.8, rc={'text.usetex': False, 'text.latex.preamble': r'\usepackage{underscore}'})

    plot_data = data.query('metric == "Mean Rank" & detector in @plot_detectors').explode('value', ignore_index=True) #.assign(value=lambda x: 1 / x.value)
    palette = matplotlib.colormaps.get_cmap('rainbow')
    palette = [palette(i) for i in np.linspace(0, 1, len(plot_detectors))]
    markers = ['D', 'o', 'X', 's', 'P', 'd']

    grid = sns.catplot(data=plot_data, kind='point', height=2.4, aspect=1.3, palette=palette, col_wrap=4,
        x='num_negatives', y='value', hue='detector', col='benchmark', hue_order=plot_detectors, col_order=benchmarks+attributes,
        markers=markers, # marker='o,
        legend='full', errorbar=None, estimator='median', dodge=0.25, markersize=5, linewidth=1, facet_kws=dict(despine=False),
    )

    # move legend to last axes
    bbox = grid.axes[7].get_position()
    sns.move_legend(grid, title='Detector', loc='lower right', bbox_to_anchor=(1.16*bbox.x1, 0.9*bbox.y0), 
        handlelength=1.0, handletextpad=0.5, columnspacing=0.3, frameon=True, ncol=2)

    # set texts
    grid.set_titles(col_template="{col_name}")
    grid.set(xlabel=None, ylabel='Rank')
    grid.fig.text(0.5, 0.01, r'Number of negative captions $N$', ha='center', va='center')

    # add major and minor ticks with autolocator
    for i, ax in enumerate(grid.axes.flat):
        ax.yaxis.set_major_locator(plt.MultipleLocator(1))
        ax.grid(which='major', axis='x', visible=True)
        # ax.spines['bottom'].set_visible(False)
        # ax.spines['top'].set_visible(True)

    grid.axes.flat[0].invert_yaxis()

    grid.fig.tight_layout()
//  [python]
def plot(df, name, label, save):
    sns.set_theme()
    sns.set_style("whitegrid")
    sns.set_context("paper")
    g = sns.factorplot(x="workload", y=name, hue="policy", data=df, kind="bar")
    g.set_axis_labels("", label)
    g.legend.set_title(None)
    if save:
        plt.savefig(f"report/img/{name}.pdf", format="pdf")
    else:
        plt.show()
//  [python]
def plot(df, name, label, save):
    sns.set_theme()
    sns.set_style("whitegrid")
    sns.set_context("paper")
    g = sns.catplot(x="workload", y=name, hue="policy", data=df, kind="bar")
    g.set_axis_labels("", label)
    g.legend.set_title(None)
    if save:
        plt.savefig(f"report/img/{name}.pdf", 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, id_vars=['cardio'], value_vars=['active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke'])


    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the collumns for the catplot to work correctly.
    #df_cat = None

    # Draw the catplot with 'sns.catplot()'
    fig = sns.factorplot(data = df_cat, kind='count',  x='variable', hue='value', col='cardio').set(ylabel = 'total').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, id_vars=['cardio'], value_vars=['active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke'])


    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the collumns for the catplot to work correctly.
    #df_cat = None

    # Draw the catplot with 'sns.catplot()'
    fig = sns.catplot(data = df_cat, kind='count',  x='variable', hue='value', col='cardio').set(ylabel = 'total').fig


    # Do not modify the next two lines
    fig.savefig('catplot.png')
    return fig
//  [python]
def plot_metrics_pc_wise(df_trs):
    """Trace-wise metrics"""
    g = sns.factorplot(x='trace_full', y='value', row='metric',
                    data=df_trs, kind='bar')
    g.set_xticklabels([])
    plt.tight_layout()
    plt.show()
//  [python]
def plot_metrics_pc_wise(df_trs):
    """Trace-wise metrics"""
    g = sns.catplot(x='trace_full', y='value', row='metric',
                    data=df_trs, kind='bar')
    g.set_xticklabels([])
    plt.tight_layout()
    plt.show()
//  [python]
def plot_metrics_optype_wise(df_tot):
    df_tot = df_tot.melt(id_vars=ID_NAMES + ['PC', 'opType'],
                         value_vars=METRICS_PLOT,
                         var_name='metric')

    g = sns.factorplot(x='opType', y='value', hue='metric', data=df_tot,
                kind='bar')
    plt.show()
    print(df_tot['opType'].value_counts())
//  [python]
def plot_metrics_optype_wise(df_tot):
    df_tot = df_tot.melt(id_vars=ID_NAMES + ['PC', 'opType'],
                         value_vars=METRICS_PLOT,
                         var_name='metric')

    sns.catplot(x='opType', y='value', hue='metric', data=df_tot,
                kind='bar')
    plt.show()
    print(df_tot['opType'].value_counts())
//  [python]
def make_dataset_plots(m: str = 'metrics.hits_at_k.avg.10'):
    u = {
        m: ('hits_at_10', 'Hits@10', {}),
        'times.training': ('time', 'Time (s)', {'xscale': 'log'}),
    }

    df = read_experiment_collation()
    df['dataset'] = df['dataset'].map(lambda s: datasets[s].__name__)

    for x, (op, label, setters) in u.items():
        g = sns.factorplot(
            x=x,
            y='model',
            data=df,
            col='dataset',
            col_wrap=2,
            kind='bar',
            order=sorted(df['model'].unique()),
        )
        g.set_titles(template='{col_name}', size=20)
        g.set_ylabels('')
        g.set_xlabels(label)
        g.set(**setters)
        g.fig.tight_layout()
        g.savefig(os.path.join(PLOTS_DIRECTORY, f'overview_{op}.pdf'))
        g.savefig(os.path.join(PLOTS_DIRECTORY, f'overview_{op}.png'), dpi=300)
        plt.close(g.fig)

    g = sns.FacetGrid(
        data=df,
        col='dataset',
        col_wrap=2,
        hue='model',
        hue_order=sorted(df['model'].unique()),
        legend_out=True,
    )
    g.map(sns.scatterplot, 'times.training', m, alpha=0.5)
    g.set_titles(template='{col_name}')
    g.set(xscale='log', xlabel='Time (s)', ylabel='Hits@10')
    g.fig.tight_layout()
    g.savefig(os.path.join(PLOTS_DIRECTORY, f'overview_scatter.pdf'))
    g.savefig(os.path.join(PLOTS_DIRECTORY, f'overview_scatter.png'), dpi=300)
    plt.close(g.fig)
//  [python]
def make_dataset_plots(m: str = 'metrics.hits_at_k.avg.10'):
    u = {
        m: ('hits_at_10', 'Hits@10', {}),
        'times.training': ('time', 'Time (s)', {'xscale': 'log'}),
    }

    df = read_experiment_collation()
    df['dataset'] = df['dataset'].map(lambda s: datasets[s].__name__)

    for x, (op, label, setters) in u.items():
        g = sns.catplot(
            x=x,
            y='model',
            data=df,
            col='dataset',
            col_wrap=2,
            kind='bar',
            order=sorted(df['model'].unique()),
        )
        g.set_titles(template='{col_name}', size=20)
        g.set_ylabels('')
        g.set_xlabels(label)
        g.set(**setters)
        g.fig.tight_layout()
        g.savefig(os.path.join(PLOTS_DIRECTORY, f'overview_{op}.pdf'))
        g.savefig(os.path.join(PLOTS_DIRECTORY, f'overview_{op}.png'), dpi=300)
        plt.close(g.fig)

    g = sns.FacetGrid(
        data=df,
        col='dataset',
        col_wrap=2,
        hue='model',
        hue_order=sorted(df['model'].unique()),
        legend_out=True,
    )
    g.map(sns.scatterplot, 'times.training', m, alpha=0.5)
    g.set_titles(template='{col_name}')
    g.set(xscale='log', xlabel='Time (s)', ylabel='Hits@10')
    g.fig.tight_layout()
    g.savefig(os.path.join(PLOTS_DIRECTORY, f'overview_scatter.pdf'))
    g.savefig(os.path.join(PLOTS_DIRECTORY, f'overview_scatter.png'), dpi=300)
    plt.close(g.fig)
//  [python]
def fps_plot(df, title):
    """plots graphs of timings"""
    df = df[~df.groupname.str.contains("ffmpeg_unblocked_decoding_speed")]
    df["groupname"] = df.groupname.str.split("_benchmark", expand=True)[0]
    sns.set(font_scale=2)
    g = sns.barplot(data=df, x="groupname", y="fps", palette="dark", alpha=.6)
    plt.xlabel(title)
    plt.savefig(title + ".png")
//  [python]
def fps_plot(df, title):
    """plots graphs of timings"""
    df = df[~df.groupname.str.contains("ffmpeg_unblocked_decoding_speed")]
    df["groupname"] = df.groupname.str.split("_benchmark", expand=True)[0]
    sns.set(font_scale=2)
    g = sns.catplot(data=df, kind="bar",
                    x="groupname", y="fps", palette="dark", alpha=.6, height=5, aspect=5,
                    legend=True, legend_out=True)
    plt.xlabel(title)
    plt.savefig(title + ".png")
//  [python]
def run():
    print('start generating...')
    df_fashion = load_dataset('../chart/fashion-mnist-history.csv')
    df_digit = load_dataset('../chart/mnist-digit.csv')
    df_oracle = load_dataset('../chart/oracle-history.csv')


    plot_results(df_fashion, df_digit,df_oracle)

    df = pd.read_csv('../chart/comparitive.csv')
    g = sns.barplot(
    data=df,
    x="Database", y="Accuracy", hue="Model",
    ci="sd")
    plt.show()
    g.figure.savefig('../chart/compare.pdf',bbox_inches="tight")
    print('file saved!')
//  [python]
def run():
    print('start generating...')
    df_fashion = load_dataset('../chart/fashion-mnist-history.csv')
    df_digit = load_dataset('../chart/mnist-digit.csv')
    df_oracle = load_dataset('../chart/oracle-history.csv')


    plot_results(df_fashion, df_digit,df_oracle)

    df = pd.read_csv('../chart/comparitive.csv')
    g = sns.catplot(
    data=df, kind="bar",
    x="Database", y="Accuracy", hue="Model",
    ci="sd")
    plt.show()
    g.savefig('../chart/compare.pdf',bbox_inches="tight")
    print('file saved!')
//  [python]
def plot_frac_mispred_per_pc(df_pc_norm):
    g = sns.relplot(  # x='n_instr',
        x='dynamic_executions',
        y='mpki',
        kind='scatter',
        data=df_pc_norm)
    g.ax.set_xscale('log')
    plt.show()

    n = 50
    mpki_per_k = [[] for _ in range(n)]
    for tr, df in df_pc_norm.groupby('trace_full'):
        k = min(n, len(df))
        # k max values of mpki
        m_vals = df.mpki.values
        idxs = np.argpartition(m_vals, -k)[-k:]
        mpki_sort = np.sort(m_vals[idxs])[::-1]
        m_total = np.sum(m_vals)
        for i in range(n):
            mpki_per_k[i].append(sum(mpki_sort[:i + 1]) / m_total)
    pcts = []
    for i in range(n):
        pct = np.mean(mpki_per_k[i]) * 100
        print('{}% of MPKI on average due to top {} H2Ps'.format(
            pct, i + 1))
        pcts.append(pct)
    df = pd.DataFrame({'Average % of MPKI': pcts,
                       'Top k H2Ps': np.arange(1, n + 1)})
    sns.barplot(x='Average % of MPKI', y='Top k H2Ps',
                orient='h',
                data=df)
    plt.show()
//  [python]
def plot_frac_mispred_per_pc(df_pc_norm):
    g = sns.relplot(  # x='n_instr',
        x='dynamic_executions',
        y='mpki',
        kind='scatter',
        data=df_pc_norm)
    g.ax.set_xscale('log')
    plt.show()

    n = 50
    mpki_per_k = [[] for _ in range(n)]
    for tr, df in df_pc_norm.groupby('trace_full'):
        k = min(n, len(df))
        # k max values of mpki
        m_vals = df.mpki.values
        idxs = np.argpartition(m_vals, -k)[-k:]
        mpki_sort = np.sort(m_vals[idxs])[::-1]
        m_total = np.sum(m_vals)
        for i in range(n):
            mpki_per_k[i].append(sum(mpki_sort[:i + 1]) / m_total)
    pcts = []
    for i in range(n):
        pct = np.mean(mpki_per_k[i]) * 100
        print('{}% of MPKI on average due to top {} H2Ps'.format(
            pct, i + 1))
        pcts.append(pct)
    df = pd.DataFrame({'Average % of MPKI': pcts,
                       'Top k H2Ps': np.arange(1, n + 1)})
    sns.catplot(x='Average % of MPKI', y='Top k H2Ps',
                orient='h', kind='bar',
                data=df)
    plt.show()
//  [python]
sns.set(style="whitegrid")

# Load the example exercise dataset
df = sns.load_dataset("exercise")

# Draw a pointplot to show pulse as a function of three categorical factors
g = sns.factorplot(x="time", y="pulse", hue="kind", col="diet",
                capsize=.2, palette="YlGnBu_d", height=6, aspect=.75,
                kind="point", data=df)
//  [python]
sns.set(style="whitegrid")

# Load the example exercise dataset
df = sns.load_dataset("exercise")

# Draw a pointplot to show pulse as a function of three categorical factors
g = sns.catplot(x="time", y="pulse", hue="kind", col="diet",
                capsize=.2, palette="YlGnBu_d", height=6, aspect=.75,
                kind="point", data=df)
//  [python]
def plotViolin(c, args):
    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns
    _updateFont(args.fontsize)

    c.execute(args.sql)
    entries = c.fetchall()

    # Clean data.
    if not entries:
        logging.info('No entries, nothing to draw.')
        return
    if len(entries[0]) != 2:
        raise ValueError('Must query for 2 fields, not %d.' % len(entries[0]))
    xylist = [(x, y) for (x, y) in entries if x is not None and y is not None]
    logging.info('%d entries have both fields non-None.', len(xylist))

    # From a list of tuples to two lists.
    xlist, ylist = tuple(map(list, zip(*xylist)))
    xlist = _maybeNumerizeProperty(xlist)
    ylist = _maybeNumerizeProperty(ylist)
    logging.debug('%s\n%s', str(xlist), str(ylist))

    data = pd.DataFrame({args.xlabel: xlist, args.ylabel: ylist})
    sns.violinplot(x=args.xlabel,
                y=args.ylabel,
                inner="quartiles",
                split=True,
                data=data)
    plt.xticks(rotation=args.rotate_xlabels)

    plt.xlabel(args.xlabel, fontsize=args.fontsize)
    plt.ylabel(args.ylabel, fontsize=args.fontsize)
    if args.out_path:
        logging.info('Saving to %s', args.out_path)
        plt.savefig(args.out_path)
    if args.display:
        plt.show()
//  [python]
def plotViolin(c, args):
    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns
    _updateFont(args.fontsize)

    c.execute(args.sql)
    entries = c.fetchall()

    # Clean data.
    if not entries:
        logging.info('No entries, nothing to draw.')
        return
    if len(entries[0]) != 2:
        raise ValueError('Must query for 2 fields, not %d.' % len(entries[0]))
    xylist = [(x, y) for (x, y) in entries if x is not None and y is not None]
    logging.info('%d entries have both fields non-None.', len(xylist))

    # From a list of tuples to two lists.
    xlist, ylist = tuple(map(list, zip(*xylist)))
    xlist = _maybeNumerizeProperty(xlist)
    ylist = _maybeNumerizeProperty(ylist)
    logging.debug('%s\n%s', str(xlist), str(ylist))

    data = pd.DataFrame({args.xlabel: xlist, args.ylabel: ylist})
    sns.catplot(x=args.xlabel,
                y=args.ylabel,
                kind="violin",
                inner="quartiles",
                split=True,
                data=data)
    plt.xticks(rotation=args.rotate_xlabels)

    plt.xlabel(args.xlabel, fontsize=args.fontsize)
    plt.ylabel(args.ylabel, fontsize=args.fontsize)
    if args.out_path:
        logging.info('Saving to %s', args.out_path)
        plt.savefig(args.out_path)
    if args.display:
        plt.show()
//  [python]
def create_dint_ratios_grouped_bar_plot(pos_dintr_dic, neg_dintr_dic, out_plot,
                                        disable_title=False,
                                        theme=1):
    """
    Create a grouped bar plot, showing the di-nucleotide ratios (16 classes)
    in the positive and negative set.
    Input ratio dictionaries for positives and negatives, with key being
    di-nucleotide and value the ratio.
    Create a dataframe using Pandas, and use seaborn for plotting.
    Store plot in out_plot.

    MV colors:
    #69e9f6, #f154b2

    """

    # Checker.
    assert pos_dintr_dic, "given dictionary pos_dintr_dic empty"
    assert neg_dintr_dic, "given dictionary neg_dintr_dic empty"
    # Make pandas dataframe.
    pos_label = "Positives"
    neg_label = "Negatives"
    data = {'set': [], 'dint': [], 'perc': []}
    for dint in pos_dintr_dic:
        data['set'].append(pos_label)
        data['dint'].append(dint)
        data['perc'].append(pos_dintr_dic[dint])
    for dint in neg_dintr_dic:
        data['set'].append(neg_label)
        data['dint'].append(dint)
        data['perc'].append(neg_dintr_dic[dint])
    df = pd.DataFrame (data, columns = ['set','dint', 'perc'])

    if theme == 1:
        # Make plot.
        sns.set(style="darkgrid")
        g = sns.barplot(x="dint", y="perc", hue="set", data=df, palette=["#69e9f6", "#f154b2"],
                        edgecolor="lightgrey")
        g.figure.set_figwidth(16)
        g.figure.set_figheight(4)
        # Modify axes.
        ax = g.axes
        ax.set_ylabel("Percentage (%)",fontsize=20)
        ax.set(xlabel=None)
        ax.tick_params(axis='x', labelsize=20)
        ax.tick_params(axis='y', labelsize=16)
        if not disable_title:
            ax.axes.set_title("Di-nucleotide distribution", fontsize=22)
        # Add legend at specific position.
        plt.legend(loc=(1.01, 0.4), fontsize=16)
        g.figure.savefig(out_plot, dpi=100, bbox_inches='tight')

    elif theme == 2:
        text_color = "#fcc826"
        plot_color = "#fd3b9d"
        box_color = "#2f19f3"
        # Make plot.
        sns.set(style="darkgrid", rc={ "axes.labelcolor": text_color, "text.color": text_color, "xtick.color": text_color, "ytick.color": text_color, "grid.color": plot_color, "axes.edgecolor": plot_color})

        g = sns.barplot(x="dint", y="perc", hue="set", data=df, palette=["blue", "darkblue"],
                        edgecolor="#fcc826")
        g.figure.set_figwidth(16)
        g.figure.set_figheight(4)
        # Modify axes.
        ax = g.axes
        ax.set_ylabel("Percentage (%)",fontsize=20)
        ax.set(xlabel=None)
        ax.tick_params(axis='x', labelsize=20)
        ax.tick_params(axis='y', labelsize=16)
        if not disable_title:
            ax.axes.set_title("Di-nucleotide distribution", fontsize=22)
        # Add legend at specific position.
        plt.legend(loc=(1.01, 0.4), fontsize=16, framealpha=0)
        g.figure.savefig(out_plot, dpi=100, bbox_inches='tight', transparent=True)
//  [python]
def cat_plot(
    indices: IndicesOutput, plot_per="variable", kind="bar", col_wrap=None, **kwargs
):
    """
    Uses the `seaborn.catplot`_ to plot the indices.

    Args:
        indices (IndicesOutput): computed indices
        plot_per (str): can be either `variable` or `index`, when set to `variable`
            there is one graph per variable, each graph showing the values of all
            indices. Respectively setting to `index` will build one graph per index,
            each showing the values for all variable.
        kind (str): kind of visualization to produce, can be one of `strip`, `swarm`,
            `box`, `violin`, `boxen`, `point`, `bar`.
        col_wrap (Optional(int)): “Wrap” the column variable at this width, so that
            the column facets span multiple rows.
        **kwargs: extra arguments passed to [seaborn.catplot](
            https://seaborn.pydata.org/generated/seaborn.catplot.html#seaborn.catplot).

    Returns:
        a matplotlib axes object

    """
    assert plot_per.lower().strip() in {"variable", "index", "indices"}
    indices_names = indices.values.columns
    variable_names = indices.values.index
    data = indices.runs.stack().reset_index()
    data.rename(
        columns={"level_0": "variable", "level_1": "index", 0: "value"}, inplace=True
    )
    if plot_per == "variable":
        col = "variable"
        x = "index"
        order = indices_names
    else:
        col = "index"
        x = "variable"
        order = variable_names
    ax = sns.catplot(
        data=data,
        x=x,
        y="value",
        col=col,
        kind=kind,
        col_wrap=col_wrap,
        order=order,
        **kwargs
    )
    ax.set(ylim=(0.0, 1.0))
    ax.set_xticklabels(rotation=45, horizontalalignment="right")
    return ax
//  [python]
def _make_main_metric_plot(df: pd.DataFrame, palette: dict, opponent: str, outpath: Path) -> None:
    #   Calculate error bars
    error_bars = {}
    for ix, row in df.iterrows():
        winrate = row["player_0_win_ratio"]
        # standard error of the mean (SEM) for binary variables
        # sqrt(p * (1 - p) / n)
        sem = (winrate * (1 - winrate) / row["num_rounds"]) ** 0.5
        error_bars[ix] = (winrate - 2 * sem, winrate + 2 * sem)

    #   Duplicate the rows so that `errorbar=func` argument in `sns.catplot` works.
    #   This is a super-ugly fix, but is probably "cleanest" from the POV of the
    #   amount of code written.
    duplicated_rows_df = pd.concat([df, df], ignore_index=True)

    g = sns.barplot(
        data=duplicated_rows_df,
        legend=False,
        x="player_0",
        y="player_0_win_ratio",
        palette=palette,
    )
    g.set(ylim=(0, 1))
    g.despine(left=True)
    g.set(title=f"Win ratio against {opponent}")
    g.set(xlabel=None, ylabel="% of rounds won")
    plt.tight_layout()
    plt.savefig(outpath)
    plt.show()
//  [python]
def _make_main_metric_plot(df: pd.DataFrame, palette: dict, opponent: str, outpath: Path) -> None:
    #   Calculate error bars
    error_bars = {}
    for ix, row in df.iterrows():
        winrate = row["player_0_win_ratio"]
        # standard error of the mean (SEM) for binary variables
        # sqrt(p * (1 - p) / n)
        sem = (winrate * (1 - winrate) / row["num_rounds"]) ** 0.5
        error_bars[ix] = (winrate - 2 * sem, winrate + 2 * sem)

    #   Duplicate the rows so that `errorbar=func` argument in `sns.catplot` works.
    #   This is a super-ugly fix, but is probably "cleanest" from the POV of the
    #   amount of code written.
    duplicated_rows_df = pd.concat([df, df], ignore_index=True)

    g = sns.catplot(
        data=duplicated_rows_df,
        kind="bar",
        legend=False,
        x="player_0",
        y="player_0_win_ratio",
        errorbar=lambda x: error_bars[x.index[0]],
        errwidth=1,
        capsize=0.1,
        palette=palette,
        aspect=1.5,
    )
    g.set(ylim=(0, 1))
    g.despine(left=True)
    g.set(title=f"Win ratio against {opponent}")
    g.set(xlabel=None, ylabel="% of rounds won")
    plt.tight_layout()
    plt.savefig(outpath)
    plt.show()
//  [python]
def plot_tools_performance():
    res_path = r'E:/LSSDS/CodART/Experimental1/experimental1_excels_merged.xlsx'
    df = pd.read_excel(res_path, sheet_name='RelatedWorks', index_col=False)

    # df.drop(columns=[])

    g = sns.factorplot(
        data=df,
        x='Project',
        y='Manual precision',
        hue='Tool',
        kind='bar',
        ci=95,
        errwidth=0.5,
        size=6.0,
        aspect=1.5,
        legend_out=False, legend=True, dodge=True,
        palette=sns.color_palette('tab10', n_colors=3),
        estimator=np.mean,
    )

    num_locations = 6
    hatches = itertools.cycle(['/', '\\', '//'])
    for i, bar in enumerate(g.axes[0, 0].patches):
        if i % num_locations == 0:
            hatch = next(hatches)
        bar.set_hatch(hatch)
        bar.set_width(0.20)

    plt.legend(ncol=3, fancybox=True,)

    # g.despine(left=True)
    # plt.legend(loc='upper center')
    # g.axes[0].legend(loc='upper center')
    plt.tight_layout()
    plt.show()
//  [python]
def plot_tools_performance():
    res_path = r'E:/LSSDS/CodART/Experimental1/experimental1_excels_merged.xlsx'
    df = pd.read_excel(res_path, sheet_name='RelatedWorks', index_col=False)

    # df.drop(columns=[])

    g = sns.catplot(
        data=df,
        x='Project',
        y='Manual precision',
        hue='Tool',
        kind='bar',
        ci=95,
        errwidth=0.5,
        height=6.0,
        aspect=1.5,
        legend_out=False, legend=True, dodge=True,
        palette=sns.color_palette('tab10', n_colors=3),
        estimator=np.mean,
    )

    num_locations = 6
    hatches = itertools.cycle(['/', '\\', '//'])
    for i, bar in enumerate(g.axes[0, 0].patches):
        if i % num_locations == 0:
            hatch = next(hatches)
        bar.set_hatch(hatch)
        bar.set_width(0.20)

    plt.legend(ncol=3, fancybox=True,)

    # g.despine(left=True)
    # plt.legend(loc='upper center')
    # g.axes[0].legend(loc='upper center')
    plt.tight_layout()
    plt.show()
//  [python]
def draw_stateful(df2, resource):
    df = df2[df2["Resource"] == resource]

    avgs = df.groupby(['Limit']).mean().reset_index()
    avgs["Benchmark"] = "Mean"
    df = pd.concat([df,avgs], axis=0, ignore_index=True, sort=False)

    # fig, ax = plt.subplots(figsize=(15,3))
    set_style()
    ax = sns.factorplot(x="Benchmark", y="Execution Time Improvement", hue="Limit", data=df, kind="bar", 
                    palette=("Purples"), size=6, aspect=1.2, legend=False)
    ax.set_xticklabels(rotation=90)
    ax.fig.tight_layout()

    plt.legend(loc=("upper center"),
            bbox_to_anchor=(.50, 1.40),
            ncol=5,
            prop={'size': 15},
            title="Adaptation Limit",
    )
    ax.axes.flatten()[0].set_ylim(df["Execution Time Improvement"].min()-0.02, df["Execution Time Improvement"].max()+0.02)
    ax.axes.flatten()[0].set_ylabel('Speedup \nover Shared', fontsize = 20)
    axes = ax.axes.flatten()
    for ax in axes:
        ax.set_xlabel("")
        for i, bar in enumerate(ax.patches):
            bar.set_edgecolor('black')

    plt.savefig("fig-adaptive-{}.pdf".format(resource), bbox_inches='tight')