jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_distributions(data, marker, hue, palette, out=None):
    # Create canvas
    fig, ax = plt.subplots(1, 1, figsize=(10, 10))

    # Plot
    sns.violinplot(data=data, x=hue, y=marker, hue=hue, palette=palette, ax=ax)
    ax.set_title(f"{marker} Intensity distribution", fontsize=20)
    sns.despine(left=True)
    plt.tight_layout()

    # Save figure
    if out is not None:
        out = [out] if isinstance(out, str) else out
        for f in out:
            fig.savefig(f, dpi=300)
//  [python]
def plot_distributions(data, marker, hue, palette, out=None):
    # Create canvas
    fig, ax = plt.subplots(1, 1, figsize=(10, 10))

    # Plot
    sns.violinplot(data=data, x=hue, y=marker, hue=hue, palette=palette, ax=ax)
    ax.set_title(f"{marker} Intensity distribution", fontsize=20)
    sns.utils.despine(left=True)
    plt.tight_layout()

    # Save figure
    if out is not None:
        out = [out] if isinstance(out, str) else out
        for f in out:
            fig.savefig(f, dpi=300)
//  [python]
def make_plot(embedding, labels, save_dir, file_name=file_name,name="Emb type", description="details"):
    sns_plot = sns.scatterplot(x=embedding[:,0], y=embedding[:,1], hue=labels, s=14, palette=custom_palette, linewidth=0, alpha=0.9)
    plt.suptitle(f"{name}_{file_name}", fontsize=8)
    sns_plot.tick_params(labelbottom=False)
    sns_plot.tick_params(labelleft=False)
    sns_plot.tick_params(bottom=False)
    sns_plot.tick_params(left=False)
    sns_plot.set_title("CLS Token embedding of "+str(len(labels))+" cells with a dimensionality of "+str(features.shape[1])+" \n"+description, fontsize=6)
    sns.move_legend(sns_plot, "lower left", title='Classes', prop={'size': 5}, title_fontsize=6, markerscale=0.5)
    sns.set(rc={"figure.figsize":(14, 10)})
    sns.despine(bottom = True, left = True)
    sns_plot.figure.savefig(f"{save_dir}{file_name}{name}.png", dpi=325)
    sns_plot.figure.savefig(f"{save_dir}pdf_format/{file_name}{name}.pdf")
    plt.close()
//  [python]
def make_plot(embedding, labels, save_dir, file_name=file_name,name="Emb type", description="details"):
    sns_plot = sns.scatterplot(x=embedding[:,0], y=embedding[:,1], hue=labels, s=14, palette=custom_palette, linewidth=0, alpha=0.9)
    plt.suptitle(f"{name}_{file_name}", fontsize=8)
    sns_plot.tick_params(labelbottom=False)
    sns_plot.tick_params(labelleft=False)
    sns_plot.tick_params(bottom=False)
    sns_plot.tick_params(left=False)
    sns_plot.set_title("CLS Token embedding of "+str(len(labels))+" cells with a dimensionality of "+str(features.shape[1])+" \n"+description, fontsize=6)
    sns.move_legend(sns_plot, "lower left", title='Classes', prop={'size': 5}, title_fontsize=6, markerscale=0.5)
    sns.set(rc={"figure.figsize":(14, 10)})
    sns.utils.despine(bottom = True, left = True)
    sns_plot.figure.savefig(f"{save_dir}{file_name}{name}.png", dpi=325)
    sns_plot.figure.savefig(f"{save_dir}pdf_format/{file_name}{name}.pdf")
    plt.close()
//  [python]
def create_data_summary_plot(data_df, subplot_side_length = 3.0, subplot_font_scale = 0.5, max_title_length = 30):

    df = pd.DataFrame(data_df)

    # determine number of plots
    n_plots = len(data_df.columns)
    n_cols = int(np.round(np.sqrt(n_plots)))
    n_rows = int(np.round(n_plots / n_cols))
    assert n_cols * n_rows >= n_plots

    colnames = df.columns.tolist()
    plot_titles = [c[:max_title_length] for c in colnames]

    f, axarr = plt.subplots(n_rows, n_cols, figsize=(subplot_side_length * n_rows, subplot_side_length * n_cols), sharex = False, sharey = True)
    sns.despine(left = True)

    n = 0
    with sns.plotting_context(font_scale = subplot_font_scale):
        for i in range(n_rows):
            for j in range(n_cols):

                ax = axarr[i][j]

                if n < n_plots:

                    bar_color = 'g' if n == 0 else 'b'
                    vals = df[colnames[n]]
                    unique_vals = np.unique(vals)

                    sns.distplot(a = vals, kde = False, color = bar_color, ax = axarr[i][j], hist_kws = {'edgecolor': "k", 'linewidth': 0.5})

                    ax.xaxis.label.set_visible(False)
                    ax.text(.5, .9, plot_titles[n], horizontalalignment = 'center', transform = ax.transAxes, fontsize = 10)

                    if len(unique_vals) == 2:
                        ax.set_xticks(unique_vals)

                    n += 1
                else:
                    ax.set_visible(False)

    plt.tight_layout()
    plt.show()

    return f, axarr
//  [python]
def create_data_summary_plot(data_df, subplot_side_length = 3.0, subplot_font_scale = 0.5, max_title_length = 30):

    df = pd.DataFrame(data_df)

    # determine number of plots
    n_plots = len(data_df.columns)
    n_cols = int(np.round(np.sqrt(n_plots)))
    n_rows = int(np.round(n_plots / n_cols))
    assert n_cols * n_rows >= n_plots

    colnames = df.columns.tolist()
    plot_titles = [c[:max_title_length] for c in colnames]

    f, axarr = plt.subplots(n_rows, n_cols, figsize=(subplot_side_length * n_rows, subplot_side_length * n_cols), sharex = False, sharey = True)
    sns.utils.despine(left = True)

    n = 0
    with sns.plotting_context(font_scale = subplot_font_scale):
        for i in range(n_rows):
            for j in range(n_cols):

                ax = axarr[i][j]

                if n < n_plots:

                    bar_color = 'g' if n == 0 else 'b'
                    vals = df[colnames[n]]
                    unique_vals = np.unique(vals)

                    sns.distplot(a = vals, kde = False, color = bar_color, ax = axarr[i][j], hist_kws = {'edgecolor': "k", 'linewidth': 0.5})

                    ax.xaxis.label.set_visible(False)
                    ax.text(.5, .9, plot_titles[n], horizontalalignment = 'center', transform = ax.transAxes, fontsize = 10)

                    if len(unique_vals) == 2:
                        ax.set_xticks(unique_vals)

                    n += 1
                else:
                    ax.set_visible(False)

    plt.tight_layout()
    plt.show()

    return f, axarr
//  [python]
def plot_box( self, fname_out = None):		
		sns.boxplot(x="Method", y="r2", data=self.df_best_expand, palette="PRGn")
		sns.despine(offset=10, trim=True)
		plt.ylabel( r"$r^2$")
		plt.xlabel( "Methods")

		if fname_out is not None:
			plt.savefig( fname_out) # index should be stored.
		elif self.fname is not None:
			fname_out = self.fname[:-4] + '_box.eps'
			print( 'Default: the figure of self.df_best_expand is saved to', fname_out)
			plt.savefig( fname_out)
//  [python]
def plot_box( self, fname_out = None):		
		sns.boxplot(x="Method", y="r2", data=self.df_best_expand, palette="PRGn")
		sns.utils.despine(offset=10, trim=True)
		plt.ylabel( r"$r^2$")
		plt.xlabel( "Methods")

		if fname_out is not None:
			plt.savefig( fname_out) # index should be stored.
		elif self.fname is not None:
			fname_out = self.fname[:-4] + '_box.eps'
			print( 'Default: the figure of self.df_best_expand is saved to', fname_out)
			plt.savefig( fname_out)
//  [python]
def scplot_data(col1, col2, data, hue_col, label1, label2, xls, yls, sz=8):
    
    # Make the  scatter plot on the DataFrame
    jp = sns.lmplot(col1, col2, data,
                    fit_reg=False, hue=hue_col, size=sz, scatter_kws ={'s': 60})
    
    # Decorate the plot and set limits
    jp.set_axis_labels(label1, label2)

    jp.axes[0,0].set_xlim(xls)
    jp.axes[0,0].set_ylim(yls)

    sns.despine(offset=0, trim=True)
    sns.set(style="ticks", font_scale=2.0)
//  [python]
def scplot_data(col1, col2, data, hue_col, label1, label2, xls, yls, sz=8):
    
    # Make the  scatter plot on the DataFrame
    jp = sns.lmplot(col1, col2, data,
                    fit_reg=False, hue=hue_col, size=sz, scatter_kws ={'s': 60})
    
    # Decorate the plot and set limits
    jp.set_axis_labels(label1, label2)

    jp.axes[0,0].set_xlim(xls)
    jp.axes[0,0].set_ylim(yls)

    sns.utils.despine(offset=0, trim=True)
    sns.set(style="ticks", font_scale=2.0)
//  [python]
sns.set_color_codes("muted")
g =sns.barplot(x="Cured/Discharged/Migrated", y="Name of State / UT", data=data,
            label="Recovered", color="g", ci=None)


# Add a legend and informative axis label
ax.legend(ncol=2, loc="lower right", frameon=True)
ax.set(xlim=(0, 200), ylabel="",
       xlabel="Cases, (dy/dt,d2y/dt2,Days since first case, Total cases)")
sns.despine(left=True, bottom=True)
//  [python]
sns.set_color_codes("muted")
g =sns.barplot(x="Cured/Discharged/Migrated", y="Name of State / UT", data=data,
            label="Recovered", color="g", ci=None)


# Add a legend and informative axis label
ax.legend(ncol=2, loc="lower right", frameon=True)
ax.set(xlim=(0, 200), ylabel="",
       xlabel="Cases, (dy/dt,d2y/dt2,Days since first case, Total cases)")
sns.utils.despine(left=True, bottom=True)
//  [python]
def splot_data(data, mdata, z, label1, label2, sz, grid_size = 100): #, xls, yls, sz):

    cmap_back = ListedColormap(sns.hls_palette(3, l=.4, s=.1))
    cmap_pts = ListedColormap(sns.hls_palette(3, l=.9, s=.9))

    sns.set(style="white")
    sns.set(style="ticks", font_scale=2.0)
    fig, ax = plt.subplots(figsize=(10,6))
    ax.set_aspect('equal')

    # Decorate the plot
    ax.set_xlabel(label1)
    ax.set_ylabel(label2)
    
    # We need grid points and values to make the colormesh plot
    xx = mdata[:, 0].reshape((grid_size, grid_size))
    yy = mdata[:, 1].reshape((grid_size, grid_size))
    zz = z.reshape((grid_size, grid_size))

    plt.pcolormesh(xx, yy, zz, cmap=cmap_back)
    
    # Now draw the points, with bolder colors.
    plt.scatter(data[:, 0], data[:, 1], c=data[:, 2], s=sz, cmap=cmap_pts)

    sns.despine(offset=0.25, trim=True)
//  [python]
def splot_data(data, mdata, z, label1, label2, sz, grid_size = 100): #, xls, yls, sz):

    cmap_back = ListedColormap(sns.hls_palette(3, l=.4, s=.1))
    cmap_pts = ListedColormap(sns.hls_palette(3, l=.9, s=.9))

    sns.set(style="white")
    sns.set(style="ticks", font_scale=2.0)
    fig, ax = plt.subplots(figsize=(10,6))
    ax.set_aspect('equal')

    # Decorate the plot
    ax.set_xlabel(label1)
    ax.set_ylabel(label2)
    
    # We need grid points and values to make the colormesh plot
    xx = mdata[:, 0].reshape((grid_size, grid_size))
    yy = mdata[:, 1].reshape((grid_size, grid_size))
    zz = z.reshape((grid_size, grid_size))

    plt.pcolormesh(xx, yy, zz, cmap=cmap_back)
    
    # Now draw the points, with bolder colors.
    plt.scatter(data[:, 0], data[:, 1], c=data[:, 2], s=sz, cmap=cmap_pts)

    sns.utils.despine(offset=0.25, trim=True)
//  [python]
def plot_go_enrichment(x_col='bonferonni_corrected_negative_log_p_value',
                       data=None, ax=None, max_categories=10,
                       yticklabels='go_name',
                       **kwargs):
    data = data.sort_values(x_col, ascending=False)
    if data.shape[0] > max_categories:
        data = data.iloc[:max_categories, :]
    if ax is None:
        ax = plt.gca()

    bottom = np.arange(data.shape[0])
    width = data[x_col]
    # width = -np.log10(data[x_col])
    ax.barh(bottom, width, **kwargs)
    ax.set(yticks=bottom + 0.4, yticklabels=data[yticklabels],
           xlabel='$-\log_{10}(q)$', ylim=(0, bottom.max() + 1))
    sns.despine()
    return ax
//  [python]
def plot_go_enrichment(x_col='bonferonni_corrected_negative_log_p_value',
                       data=None, ax=None, max_categories=10,
                       yticklabels='go_name',
                       **kwargs):
    data = data.sort_values(x_col, ascending=False)
    if data.shape[0] > max_categories:
        data = data.iloc[:max_categories, :]
    if ax is None:
        ax = plt.gca()

    bottom = np.arange(data.shape[0])
    width = data[x_col]
    # width = -np.log10(data[x_col])
    ax.barh(bottom, width, **kwargs)
    ax.set(yticks=bottom + 0.4, yticklabels=data[yticklabels],
           xlabel='$-\log_{10}(q)$', ylim=(0, bottom.max() + 1))
    sns.utils.despine()
    return ax
//  [python]
def plot_sims():
    """Plot simulations"""
    fig, ax = plt.subplots(nrows=4, ncols=5, figsize=(28, 24))

    plt.suptitle("Independence Simulations", y=0.93, va="baseline")

    for i, row in enumerate(ax):
        for j, col in enumerate(row):
            count = 5 * i + j
            sim_title = SIM_TITLES[count]
            sim = list(SIMULATIONS.values())[count]

            # the multiplicative noise and independence simulation don't have a noise
            # parameter
            if sim_title in ["Noise", "Independence"]:
                x, y = sim(NO_NOISE, 1)
                x_no_noise, y_no_noise = x, y
            else:
                x, y = sim(NOISY, 1, noise=True)
                x_no_noise, y_no_noise = sim(NO_NOISE, 1)

            # plot the noise and noise-free sims
            col.scatter(x, y, label="Noisy")
            col.scatter(x_no_noise, y_no_noise, label="No Noise")

            # make the plot look pretty
            col.set_title("{}".format(sim_title))
            col.set_xticks([])
            col.set_yticks([])
            if count == 16:
                col.set_ylim([-1, 1])
            sns.despine(left=True, bottom=True, right=True)

    leg = plt.legend(
        bbox_to_anchor=(0.5, 0.1),
        bbox_transform=plt.gcf().transFigure,
        ncol=5,
        loc="upper center",
    )
    leg.get_frame().set_linewidth(0.0)
    for legobj in leg.legendHandles:
        legobj.set_linewidth(5.0)
    plt.subplots_adjust(hspace=0.75)
//  [python]
def plot_sims():
    """Plot simulations"""
    fig, ax = plt.subplots(nrows=4, ncols=5, figsize=(28, 24))

    plt.suptitle("Independence Simulations", y=0.93, va="baseline")

    for i, row in enumerate(ax):
        for j, col in enumerate(row):
            count = 5 * i + j
            sim_title = SIM_TITLES[count]
            sim = list(SIMULATIONS.values())[count]

            # the multiplicative noise and independence simulation don't have a noise
            # parameter
            if sim_title in ["Noise", "Independence"]:
                x, y = sim(NO_NOISE, 1)
                x_no_noise, y_no_noise = x, y
            else:
                x, y = sim(NOISY, 1, noise=True)
                x_no_noise, y_no_noise = sim(NO_NOISE, 1)

            # plot the noise and noise-free sims
            col.scatter(x, y, label="Noisy")
            col.scatter(x_no_noise, y_no_noise, label="No Noise")

            # make the plot look pretty
            col.set_title("{}".format(sim_title))
            col.set_xticks([])
            col.set_yticks([])
            if count == 16:
                col.set_ylim([-1, 1])
            sns.utils.despine(left=True, bottom=True, right=True)

    leg = plt.legend(
        bbox_to_anchor=(0.5, 0.1),
        bbox_transform=plt.gcf().transFigure,
        ncol=5,
        loc="upper center",
    )
    leg.get_frame().set_linewidth(0.0)
    for legobj in leg.legendHandles:
        legobj.set_linewidth(5.0)
    plt.subplots_adjust(hspace=0.75)
//  [python]
def plot_prediction_summary(
    device_names, signal_names, times, OBS, MU, STD, device_ids, predict_style, fixYaxis=False,
):
    """Compare the simulation against the data for the highest weighted sample"""

    nplots = MU.shape[1]
    unique_devices = np.unique(device_ids)
    ndevices = len(unique_devices)

    f, axs = pp.subplots(ndevices, nplots, sharex=True, figsize=(10, 2 * ndevices))
    for iu, device_id in enumerate(unique_devices):
        locs = np.where(device_ids == device_id)[0]
        for idx in range(nplots):
            if ndevices > 1:
                ax = axs[iu, idx]
            else:
                ax = axs[idx]
            w_mu = MU[locs, idx, :]
            w_std = STD[locs, idx, :]

            for mu, std in zip(w_mu, w_std):
                ax.fill_between(times, mu - 2 * std, mu + 2 * std, color="grey", alpha=0.1)

            ax.plot(times, OBS[locs, idx, :].T, "r-", lw=1, alpha=1)
            ax.plot(times, w_mu.T, predict_style, lw=1, alpha=0.75, color="k")
            if fixYaxis:
                ax.set_ylim(-0.2, 1.2)

            if iu == ndevices - 1:
                ax.set_xlabel("Time (h)")
            if iu == 0:
                ax.set_title(signal_names[idx])
            if idx == 0:
                ax.set_ylabel(device_names[device_id])
    pp.tight_layout()
    sns.despine()

    return f
//  [python]
def plot_prediction_summary(
    device_names, signal_names, times, OBS, MU, STD, device_ids, predict_style, fixYaxis=False,
):
    """Compare the simulation against the data for the highest weighted sample"""

    nplots = MU.shape[1]
    unique_devices = np.unique(device_ids)
    ndevices = len(unique_devices)

    f, axs = pp.subplots(ndevices, nplots, sharex=True, figsize=(10, 2 * ndevices))
    for iu, device_id in enumerate(unique_devices):
        locs = np.where(device_ids == device_id)[0]
        for idx in range(nplots):
            if ndevices > 1:
                ax = axs[iu, idx]
            else:
                ax = axs[idx]
            w_mu = MU[locs, idx, :]
            w_std = STD[locs, idx, :]

            for mu, std in zip(w_mu, w_std):
                ax.fill_between(times, mu - 2 * std, mu + 2 * std, color="grey", alpha=0.1)

            ax.plot(times, OBS[locs, idx, :].T, "r-", lw=1, alpha=1)
            ax.plot(times, w_mu.T, predict_style, lw=1, alpha=0.75, color="k")
            if fixYaxis:
                ax.set_ylim(-0.2, 1.2)

            if iu == ndevices - 1:
                ax.set_xlabel("Time (h)")
            if iu == 0:
                ax.set_title(signal_names[idx])
            if idx == 0:
                ax.set_ylabel(device_names[device_id])
    pp.tight_layout()
    sns.utils.despine()

    return f
//  [python]
def plot_dist_matrix(matrix, fasta_names, heatmap_out, dendrogram_out, cluster_threshold, clustering_out):
    """Cluster the distance matrix hierarchically and plot using seaborn.
    Average linkage method is used."""
    # Load required modules for plotting
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    from scipy.cluster.hierarchy import dendrogram, linkage, fcluster

    # Create
    pdm = pd.DataFrame(matrix, index=fasta_names, columns=fasta_names)

    # Create linkage clustering
    link = linkage(pdm, metric='euclidean', method='average')
    flat_clusters = fcluster(link, cluster_threshold, criterion='distance')

    clustering = pd.Series(dict(list(zip(fasta_names, flat_clusters))))
    clustering.to_csv(clustering_out, sep='\t')

    # Plot heatmap
    figsizex = max(10, len(fasta_names) / 4)
    clustergrid = sns.clustermap(pdm, col_linkage=link, row_linkage=link,
            figsize=(figsizex, figsizex))
    clustergrid.savefig(heatmap_out)

    # Plot dendrogram
    sns.set_style('white')
    figsizey = max(10, len(fasta_names) / 8)
    f, ax = plt.subplots(figsize=(figsizex, figsizey))
    dendrogram(link, labels=pdm.index, ax=ax)
    no_spine = {'left': True, 'bottom': True, 'right': True, 'top': True}
    sns.despine(**no_spine)
    plt.xticks(rotation=90)
    f.tight_layout()
    plt.savefig(dendrogram_out)
//  [python]
def plot_dist_matrix(matrix, fasta_names, heatmap_out, dendrogram_out, cluster_threshold, clustering_out):
    """Cluster the distance matrix hierarchically and plot using seaborn.
    Average linkage method is used."""
    # Load required modules for plotting
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
    from seaborn.utils import despine

    # Create
    pdm = pd.DataFrame(matrix, index=fasta_names, columns=fasta_names)

    # Create linkage clustering
    link = linkage(pdm, metric='euclidean', method='average')
    flat_clusters = fcluster(link, cluster_threshold, criterion='distance')

    clustering = pd.Series(dict(list(zip(fasta_names, flat_clusters))))
    clustering.to_csv(clustering_out, sep='\t')

    # Plot heatmap
    figsizex = max(10, len(fasta_names) / 4)
    clustergrid = sns.clustermap(pdm, col_linkage=link, row_linkage=link,
            figsize=(figsizex, figsizex))
    clustergrid.savefig(heatmap_out)

    # Plot dendrogram
    sns.set_style('white')
    figsizey = max(10, len(fasta_names) / 8)
    f, ax = plt.subplots(figsize=(figsizex, figsizey))
    dendrogram(link, labels=pdm.index, ax=ax)
    no_spine = {'left': True, 'bottom': True, 'right': True, 'top': True}
    despine(**no_spine)
    plt.xticks(rotation=90)
    f.tight_layout()
    plt.savefig(dendrogram_out)
//  [python]
def plot_relative(systems, val, kind='token_histogram'):
    fig, ax = plt.subplots(figsize=(30,20))
    lw = 8.0
    ms = 25.0
    keys = set()
    keys.update(val[kind].keys())
    for name, data in systems.items():
        keys.update(data[kind].keys())
    keys = sorted(keys)
    
    for name, data in systems.items():
        total = sum(data[kind].values())
        y = [data[kind][key]/total for key in keys]
        plt.plot(keys, y, 'o-', label=name, linewidth=lw, markersize=ms)
    
    total = sum(val[kind].values())
    y = [val[kind][key]/total for key in keys]
    plt.plot(keys, y, 'o-', label='Val', linewidth=lw, markersize=ms)
    
    plt.legend()#loc=2, bbox_to_anchor=(0, 1.1))
    plt.xticks(keys)
    plt.ylabel('Proportion')
    plt.xlabel('WordNet depth')
    sns.despine()
    plt.savefig(f'./Data/Output/wordnet_relative_{kind}.pdf')
//  [python]
def plot_relative(systems, val, kind='token_histogram'):
    fig, ax = plt.subplots(figsize=(30,20))
    lw = 8.0
    ms = 25.0
    keys = set()
    keys.update(val[kind].keys())
    for name, data in systems.items():
        keys.update(data[kind].keys())
    keys = sorted(keys)
    
    for name, data in systems.items():
        total = sum(data[kind].values())
        y = [data[kind][key]/total for key in keys]
        plt.plot(keys, y, 'o-', label=name, linewidth=lw, markersize=ms)
    
    total = sum(val[kind].values())
    y = [val[kind][key]/total for key in keys]
    plt.plot(keys, y, 'o-', label='Val', linewidth=lw, markersize=ms)
    
    plt.legend()#loc=2, bbox_to_anchor=(0, 1.1))
    plt.xticks(keys)
    plt.ylabel('Proportion')
    plt.xlabel('WordNet depth')
    sns.utils.despine()
    plt.savefig(f'./Data/Output/wordnet_relative_{kind}.pdf')
//  [python]
def plot_absolute(systems, val, kind='token_histogram'):
    fig, ax = plt.subplots(figsize=(30,20))
    lw = 8.0
    ms = 25.0
    keys = set()
    keys.update(val[kind].keys())
    for name, data in systems.items():
        keys.update(data[kind].keys())
    keys = sorted(keys)
    
    for name, data in systems.items():
        y = [data[kind][key] for key in keys]
        plt.plot(keys, y, 'o-', label=name, linewidth=lw, markersize=ms)
    
    y = [val[kind][key] for key in keys]
    plt.plot(keys, y, 'o-', label='Val', linewidth=lw, markersize=ms)
    
    plt.legend()#loc=2, bbox_to_anchor=(0, 1.1))
    plt.xticks(keys)
    plt.ylabel('Number of tokens' if kind=='token_histogram' else 'Number of types')
    plt.xlabel('WordNet depth')
    sns.despine()
    plt.savefig(f'./Data/Output/wordnet_absolute_{kind}.pdf')
//  [python]
def plot_absolute(systems, val, kind='token_histogram'):
    fig, ax = plt.subplots(figsize=(30,20))
    lw = 8.0
    ms = 25.0
    keys = set()
    keys.update(val[kind].keys())
    for name, data in systems.items():
        keys.update(data[kind].keys())
    keys = sorted(keys)
    
    for name, data in systems.items():
        y = [data[kind][key] for key in keys]
        plt.plot(keys, y, 'o-', label=name, linewidth=lw, markersize=ms)
    
    y = [val[kind][key] for key in keys]
    plt.plot(keys, y, 'o-', label='Val', linewidth=lw, markersize=ms)
    
    plt.legend()#loc=2, bbox_to_anchor=(0, 1.1))
    plt.xticks(keys)
    plt.ylabel('Number of tokens' if kind=='token_histogram' else 'Number of types')
    plt.xlabel('WordNet depth')
    sns.utils.despine()
    plt.savefig(f'./Data/Output/wordnet_absolute_{kind}.pdf')
//  [python]
def genre_bar(genre_counts, genre_list, name): 
    
    """Generates a barplot of the genres/moods in a dataset, with the corresponding percentage for each genre/mood.

    Args:
        genre_counts (pandas.Series object): Contains the different unique genres/moods as keys and the counts for each one as values.
        genre_list (list): Contains the list of all the genres/moods, each element corresponds to a recording in the dataset.
        name (str): Name of the dataset, to display as a title.

    """
    
    if len(genre_list) == 0:
        raise TypeError('genre_list can\'t be an empty list')
        return
    
    total = float(len(genre_list))
    ax = sns.barplot(x=genre_counts, y=genre_counts.keys(), orient='h', palette='PuBu_r')

    #Compute and locate percentages
    for p in ax.patches:
        loc = ax.patches[0].get_width()
        width = p.get_width()
        ax.text(loc+ 20, p.get_y()+p.get_height()/1.5, '  {:1.2f}%'.format(100*width/total), ha='left') 
        
    ax.set_xticks([])
    sns.despine(left=True, bottom=True)
    plt.show()
//  [python]
def genre_bar(genre_counts, genre_list, name): 
    
    """Generates a barplot of the genres/moods in a dataset, with the corresponding percentage for each genre/mood.

    Args:
        genre_counts (pandas.Series object): Contains the different unique genres/moods as keys and the counts for each one as values.
        genre_list (list): Contains the list of all the genres/moods, each element corresponds to a recording in the dataset.
        name (str): Name of the dataset, to display as a title.

    """
    
    if len(genre_list) == 0:
        raise TypeError('genre_list can\'t be an empty list')
        return
    
    total = float(len(genre_list))
    ax = sns.barplot(x=genre_counts, y=genre_counts.keys(), orient='h', palette='PuBu_r')

    #Compute and locate percentages
    for p in ax.patches:
        loc = ax.patches[0].get_width()
        width = p.get_width()
        ax.text(loc+ 20, p.get_y()+p.get_height()/1.5, '  {:1.2f}%'.format(100*width/total), ha='left') 
        
    ax.set_xticks([])
    sns.utils.despine(left=True, bottom=True)
    plt.show()
//  [python]
def genre_mood_bar(mood, genre_counts, pct, name): 
    
    """Generates a barplot of the relationship between genres in a dataset a group or pair of moods.

    Args:
        mood(list): Contains the list of the mood corresponding to each of the elements in genre_counts. 
        genre_counts (pandas.Series object): Contains the different genres as keys and the counts for each one as values. Each genre appears as many times as moods that we want to differentiate. 
        pct (dict): Contains all the genres as keys (as many times as moods there are) and the porcentage that each mood appears in each of the genres.
        name (str): Name of the dataset.

    """
    
    ax = sns.barplot(x=genre_counts.keys(), y=genre_counts, hue=mood, palette='Paired')

    i = 0
    for p in ax.patches:
        ax.text(p.get_x()+p.get_width()/2., p.get_height() + 10., '{:1.2f}%'.format(pct[i]), ha='center', fontsize=15) 
        i += 1

    ax.set_xlabel(name)
    ax.set_ylabel('count')
    sns.despine(left=True, bottom=True)
//  [python]
def genre_mood_bar(mood, genre_counts, pct, name): 
    
    """Generates a barplot of the relationship between genres in a dataset a group or pair of moods.

    Args:
        mood(list): Contains the list of the mood corresponding to each of the elements in genre_counts. 
        genre_counts (pandas.Series object): Contains the different genres as keys and the counts for each one as values. Each genre appears as many times as moods that we want to differentiate. 
        pct (dict): Contains all the genres as keys (as many times as moods there are) and the porcentage that each mood appears in each of the genres.
        name (str): Name of the dataset.

    """
    
    ax = sns.barplot(x=genre_counts.keys(), y=genre_counts, hue=mood, palette='Paired')

    i = 0
    for p in ax.patches:
        ax.text(p.get_x()+p.get_width()/2., p.get_height() + 10., '{:1.2f}%'.format(pct[i]), ha='center', fontsize=15) 
        i += 1

    ax.set_xlabel(name)
    ax.set_ylabel('count')
    sns.utils.despine(left=True, bottom=True)
//  [python]
def features_gen_box(g_dict, l_dict, name):

    """Generates a boxplot of the relationship between the average loudness, or any other feature, and each genre in a dataset. 
    
    Args:
        g_dict (dict): Contains the different mbdis as keys and the corresponding genres as values.
        l_dict (dict): Contains the different mbdis as keys and the corresponding average_loudness as values.
        name (str): Name of the dataset.

    """
    
    x = []
    y = []
    for mbid in g_dict:

        if mbid in l_dict: 
            x.append(g_dict[mbid])
            y.append(l_dict[mbid])
    
    ax = sns.boxplot(x=np.array(x), y=np.array(y), palette='Set3')
    
    ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
    sns.despine(left=True, bottom=True)
    ax.set_ylabel('average_loudness')
    ax.set_title(name)
//  [python]
def features_gen_box(g_dict, l_dict, name):

    """Generates a boxplot of the relationship between the average loudness, or any other feature, and each genre in a dataset. 
    
    Args:
        g_dict (dict): Contains the different mbdis as keys and the corresponding genres as values.
        l_dict (dict): Contains the different mbdis as keys and the corresponding average_loudness as values.
        name (str): Name of the dataset.

    """
    
    x = []
    y = []
    for mbid in g_dict:

        if mbid in l_dict: 
            x.append(g_dict[mbid])
            y.append(l_dict[mbid])
    
    ax = sns.boxplot(x=np.array(x), y=np.array(y), palette='Set3')
    
    ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
    sns.utils.despine(left=True, bottom=True)
    ax.set_ylabel('average_loudness')
    ax.set_title(name)
//  [python]
def year_bar(year_counts, quantiles):
    
    """Generates a barplot of the count of elements for each year. Also displays the 0.25, 0.50 and 0.75 quantiles of the distribution. 

    Args:
        year_counts (pandas.Series object): Contains the different years as keys and the counts as values. 
        quantiles (pandas.Series object): Contains the quantiles and the values. 

    """    
    
    plt.figure(figsize=(18,6))

    ax = sns.barplot(x=year_counts.keys(), y=year_counts, palette='GnBu')

    labels = set_year_labels(ax)

    ax.set_xticklabels(labels, ha="center")

    plt.axvline(quantiles[0.25], 0, 1)
    plt.axvline(quantiles[0.50], 0, 1)
    plt.axvline(quantiles[0.75], 0, 1)

    plt.ylabel('count')
    plt.xlabel('year')
    sns.despine(left=True, bottom=True)
    plt.show()
//  [python]
def year_bar(year_counts, quantiles):
    
    """Generates a barplot of the count of elements for each year. Also displays the 0.25, 0.50 and 0.75 quantiles of the distribution. 

    Args:
        year_counts (pandas.Series object): Contains the different years as keys and the counts as values. 
        quantiles (pandas.Series object): Contains the quantiles and the values. 

    """    
    
    plt.figure(figsize=(18,6))

    ax = sns.barplot(x=year_counts.keys(), y=year_counts, palette='GnBu')

    labels = set_year_labels(ax)

    ax.set_xticklabels(labels, ha="center")

    plt.axvline(quantiles[0.25], 0, 1)
    plt.axvline(quantiles[0.50], 0, 1)
    plt.axvline(quantiles[0.75], 0, 1)

    plt.ylabel('count')
    plt.xlabel('year')
    sns.utils.despine(left=True, bottom=True)
    plt.show()
//  [python]
xticklabel = ax.get_xticklabels()
yticklabel = ax.get_yticklabels()
plt.setp(xticklabel, size=7, rotation=45, horizontalalignment='right')
plt.setp(yticklabel, size=10, rotation=0, horizontalalignment='right')
sns.despine()
//  [python]
xticklabel = ax.get_xticklabels()
yticklabel = ax.get_yticklabels()
plt.setp(xticklabel, size=7, rotation=45, horizontalalignment='right')
plt.setp(yticklabel, size=10, rotation=0, horizontalalignment='right')
sns.utils.despine()
//  [python]
def key_est_bar(keys, key_counts):
    
    """Generates a barplot of the count of elements for each key and scale.

    Args:
        keys (tuple): Contains the different scales and keys, keys duplicated for each scale. 
        key_counts (dict): Contains a tuple having each key and scale combination as keys and the counts as values. 

    """    
    
    if len(key_counts) == 0:
        raise TypeError('key_counts can\'t be an empty dictionary')
        return

    #Compute percentages
    a = key_counts[0 : int(len(key_counts)/2)].values
    b = key_counts[int(len(key_counts)/2):].values

    pct = 100 * a / (a+b)
    pct = np.append(pct, 100 - pct)
    
    ax = sns.barplot(x=np.array(keys[1]), y=key_counts, hue=np.array(keys[0]), palette='Paired')

    i = 0
    for p in ax.patches:
        ax.text(p.get_x()+p.get_width()/2., p.get_height() + 10., '{:1.2f}%'.format(pct[i]), ha='center', fontsize=14) 
        i += 1

    ax.set_xlabel('tonic')
    ax.set_ylabel('count')
    sns.despine(left=True, bottom=True)
//  [python]
def key_est_bar(keys, key_counts):
    
    """Generates a barplot of the count of elements for each key and scale.

    Args:
        keys (tuple): Contains the different scales and keys, keys duplicated for each scale. 
        key_counts (dict): Contains a tuple having each key and scale combination as keys and the counts as values. 

    """    
    
    if len(key_counts) == 0:
        raise TypeError('key_counts can\'t be an empty dictionary')
        return

    #Compute percentages
    a = key_counts[0 : int(len(key_counts)/2)].values
    b = key_counts[int(len(key_counts)/2):].values

    pct = 100 * a / (a+b)
    pct = np.append(pct, 100 - pct)
    
    ax = sns.barplot(x=np.array(keys[1]), y=key_counts, hue=np.array(keys[0]), palette='Paired')

    i = 0
    for p in ax.patches:
        ax.text(p.get_x()+p.get_width()/2., p.get_height() + 10., '{:1.2f}%'.format(pct[i]), ha='center', fontsize=14) 
        i += 1

    ax.set_xlabel('tonic')
    ax.set_ylabel('count')
    sns.utils.despine(left=True, bottom=True)
//  [python]
def features_years_box(y_dict, l_dict, name):
    
    """Generates a boxplot of the relationship between the average loudness, or any other feature, and each year. 

    Args:
        y_dict (dict): Contains the different mbdis as keys and the corresponding years as values.
        l_dict (dict): Contains the different mbdis as keys and the corresponding average_loudness as values.
        name (str): Name of the feature to display.

    """  
    
    x = []
    y = []
    for mbid in y_dict:

        if mbid in l_dict and y_dict[mbid] >= 1950.0: 
            x.append(y_dict[mbid])
            y.append(l_dict[mbid]) 

    x_int = np.array(x).astype(int)
    
    plt.figure(figsize=(18,6))
    ax = sns.boxplot(x=x_int, y=np.array(y), color='xkcd:lightblue')
    
    labels = set_year_labels(ax)
    
    ax.set_xticklabels(labels, ha="center")

    plt.ylabel(name)
    plt.xlabel('year')
    sns.despine(left=True, bottom=True)
    plt.show()
//  [python]
def features_years_box(y_dict, l_dict, name):
    
    """Generates a boxplot of the relationship between the average loudness, or any other feature, and each year. 

    Args:
        y_dict (dict): Contains the different mbdis as keys and the corresponding years as values.
        l_dict (dict): Contains the different mbdis as keys and the corresponding average_loudness as values.
        name (str): Name of the feature to display.

    """  
    
    x = []
    y = []
    for mbid in y_dict:

        if mbid in l_dict and y_dict[mbid] >= 1950.0: 
            x.append(y_dict[mbid])
            y.append(l_dict[mbid]) 

    x_int = np.array(x).astype(int)
    
    plt.figure(figsize=(18,6))
    ax = sns.boxplot(x=x_int, y=np.array(y), color='xkcd:lightblue')
    
    labels = set_year_labels(ax)
    
    ax.set_xticklabels(labels, ha="center")

    plt.ylabel(name)
    plt.xlabel('year')
    sns.utils.despine(left=True, bottom=True)
    plt.show()
//  [python]
sns.set_style("whitegrid", {'axes.grid' : False})
sns.despine(left=True, bottom=False)
//  [python]
sns.set_style("whitegrid", {'axes.grid' : False})
sns.utils.despine(left=True, bottom=False)
//  [python]
def beautify_with_seaborn():
    #

    seaborn.set_style('white')
    seaborn.despine(trim=True)
    seaborn.set_context('poster')
//  [python]
def beautify_with_seaborn():
    #

    seaborn.set_style('white')
    seaborn.utils.despine(trim=True)
    seaborn.set_context('poster')
//  [python]
def plot_lorentz(cdf, per_sample=False):
    fig, ax = plt.subplots(figsize=(6,6))
    if per_sample:
        for cell in cdf:
            ax.plot(np.linspace(0,1,cdf.shape[0]), np.cumsum(cdf[cell].fillna(0).sort_values(ascending=True))/cdf[cell].sum(),label=cell,zorder=1)

    else:
        ax.plot(np.linspace(0,1,cdf.shape[0]), np.cumsum(cdf.sum(1).fillna(0).sort_values(ascending=True))/cdf.sum().sum(),label='observed',zorder=1)
        ax.plot([0,1],[0,1],c='grey',ls=':',label='optimum',zorder=1)
        plt.title('Lorenz curve, all samples')

    ax.set_ylabel('Fraction of molecules (cumulative)')
    ax.set_xlabel('Fraction of genome')
    plt.legend()
    ax.grid(zorder=0)
    sns.despine()
    return fig, ax
//  [python]
def plot_lorentz(cdf, per_sample=False):
    fig, ax = plt.subplots(figsize=(6,6))
    if per_sample:
        for cell in cdf:
            ax.plot(np.linspace(0,1,cdf.shape[0]), np.cumsum(cdf[cell].fillna(0).sort_values(ascending=True))/cdf[cell].sum(),label=cell,zorder=1)

    else:
        ax.plot(np.linspace(0,1,cdf.shape[0]), np.cumsum(cdf.sum(1).fillna(0).sort_values(ascending=True))/cdf.sum().sum(),label='observed',zorder=1)
        ax.plot([0,1],[0,1],c='grey',ls=':',label='optimum',zorder=1)
        plt.title('Lorenz curve, all samples')

    ax.set_ylabel('Fraction of molecules (cumulative)')
    ax.set_xlabel('Fraction of genome')
    plt.legend()
    ax.grid(zorder=0)
    sns.utils.despine()
    return fig, ax
//  [python]
def plot(self, target_path, title=None):
        fig, ax = plot_lorentz(self.cdf,False)

        plt.tight_layout()
        plt.savefig(target_path)
        plt.close()


        fig, ax = plt.subplots(figsize=(10,5))
        cov_per_cell = (((self.cdf>0).sum() / self.cdf.shape[0]).sort_values())
        cov_per_cell.name='fraction genome covered'
        cov_per_cell.plot.bar()

        mean_cov = cov_per_cell.mean()
        ax.axhline(mean_cov,c='green',label='mean coverage (%.3f)' % mean_cov)
        ax.set_ylabel('Fraction genome covered')
        ax.set_xlabel("Cells")
        ax.set_xticks([],[])
        sns.despine()
        plt.legend()

        plt.savefig(target_path.replace('.png', '.cell_genome_fraction.png'))
        plt.tight_layout()
        plt.close()
//  [python]
def plot(self, target_path, title=None):
        fig, ax = plot_lorentz(self.cdf,False)

        plt.tight_layout()
        plt.savefig(target_path)
        plt.close()


        fig, ax = plt.subplots(figsize=(10,5))
        cov_per_cell = (((self.cdf>0).sum() / self.cdf.shape[0]).sort_values())
        cov_per_cell.name='fraction genome covered'
        cov_per_cell.plot.bar()

        mean_cov = cov_per_cell.mean()
        ax.axhline(mean_cov,c='green',label='mean coverage (%.3f)' % mean_cov)
        ax.set_ylabel('Fraction genome covered')
        ax.set_xlabel("Cells")
        ax.set_xticks([],[])
        sns.utils.despine()
        plt.legend()

        plt.savefig(target_path.replace('.png', '.cell_genome_fraction.png'))
        plt.tight_layout()
        plt.close()
//  [python]
def plot_weight_curves(weights_table, task):
    layer_names = ['lex'] + [str(i) for i in range(1, 13)]

    f = plt.figure(figsize=(6, 3))

    for key, layers in weights_table.items():
        weights = layers[12]
        if weights is None:
            continue

        sns.lineplot(x=layer_names, y=weights, label=key[0], sort=False)

    # ax.set_title(task)
    ax = f.axes[0]
    ax.set(xlabel='Cumulative layer', ylabel='Weighted layer')
    sns.despine(left=True, bottom=True)
    f.tight_layout()

    return f
//  [python]
def plot_weight_curves(weights_table, task):
    layer_names = ['lex'] + [str(i) for i in range(1, 13)]

    f = plt.figure(figsize=(6, 3))

    for key, layers in weights_table.items():
        weights = layers[12]
        if weights is None:
            continue

        sns.lineplot(x=layer_names, y=weights, label=key[0], sort=False)

    # ax.set_title(task)
    ax = f.axes[0]
    ax.set(xlabel='Cumulative layer', ylabel='Weighted layer')
    sns.utils.despine(left=True, bottom=True)
    f.tight_layout()

    return f
//  [python]
def plot_weights(weights_table, task):
    layer_names = ['lex'] + [str(i) for i in range(1, 13)]

    for key, layers in weights_table.items():
        data = np.zeros((13, 12))

        show_plot = False
        for layer, weights in enumerate(layers):
            if weights is None:
                continue

            data[13 - len(weights):, layer - 1] = weights
            show_plot = True

        if not show_plot:
            continue

        f = plt.figure(figsize=(6, 4))
        sns.heatmap(data, xticklabels=layer_names[1:], yticklabels=list(reversed(layer_names)), annot=True)
        # ax.set_title(f'{key[0]} {task}')
        ax = f.axes[0]
        ax.set(xlabel='Cumulative layer', ylabel='Weighted layer')
        sns.despine(left=True, bottom=True)
        f.tight_layout()

        return f
//  [python]
def plot_weights(weights_table, task):
    layer_names = ['lex'] + [str(i) for i in range(1, 13)]

    for key, layers in weights_table.items():
        data = np.zeros((13, 12))

        show_plot = False
        for layer, weights in enumerate(layers):
            if weights is None:
                continue

            data[13 - len(weights):, layer - 1] = weights
            show_plot = True

        if not show_plot:
            continue

        f = plt.figure(figsize=(6, 4))
        sns.heatmap(data, xticklabels=layer_names[1:], yticklabels=list(reversed(layer_names)), annot=True)
        # ax.set_title(f'{key[0]} {task}')
        ax = f.axes[0]
        ax.set(xlabel='Cumulative layer', ylabel='Weighted layer')
        sns.utils.despine(left=True, bottom=True)
        f.tight_layout()

        return f
//  [python]
def print_2D( points,label,id_map ):
    '''
    points: N_samples * 2
    label: (int) N_samples
    id_map: map label id to its name
    '''  
    fig = plt.figure()
    #current_palette = sns.color_palette("RdBu_r", max(label)+1)
    n_cell,_ = points.shape
    if n_cell > 500:
        s = 10
    else:
        s = 20
    
    ax = plt.subplot(111)
    print( np.unique(label) )
    for i in np.unique(label):
        ax.scatter( points[label==i,0], points[label==i,1], c=current_palette[i], label=id_map[i], s=s,marker=markers_keys[i] )
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1,
                     box.width, box.height * 0.9])
        
    ax.legend(scatterpoints=1,loc='upper center',
              bbox_to_anchor=(0.5,-0.08),ncol=6,
              fancybox=True,
              prop={'size':8}
              )
    sns.despine()
    return fig
//  [python]
def print_2D( points,label,id_map ):
    '''
    points: N_samples * 2
    label: (int) N_samples
    id_map: map label id to its name
    '''  
    fig = plt.figure()
    #current_palette = sns.color_palette("RdBu_r", max(label)+1)
    n_cell,_ = points.shape
    if n_cell > 500:
        s = 10
    else:
        s = 20
    
    ax = plt.subplot(111)
    print( np.unique(label) )
    for i in np.unique(label):
        ax.scatter( points[label==i,0], points[label==i,1], c=current_palette[i], label=id_map[i], s=s,marker=markers_keys[i] )
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1,
                     box.width, box.height * 0.9])
        
    ax.legend(scatterpoints=1,loc='upper center',
              bbox_to_anchor=(0.5,-0.08),ncol=6,
              fancybox=True,
              prop={'size':8}
              )
    sns.utils.despine()
    return fig
//  [python]
def plot_overall(overall_summary):
    f = plt.figure(figsize=(6, 4))

    for metric, color in [('center', 'pastel'), ('expected', 'muted')]:
        sns.set_color_codes(color)

        x = [res[metric] for model, model_res in overall_summary.items() for task, res in model_res.items()]
        y = [task for model, model_res in overall_summary.items() for task, res in model_res.items()]
        hue = [model for model, model_res in overall_summary.items() for task, res in model_res.items()]

        sns.barplot(x=x, y=y, hue=hue, palette=color, order=[
                    'udalpino-pos', 'udlassy-pos', 'conll2002-ner', 'udlassy-dep', 'sonar-coref', 'udalpino-dep'])

    ax = f.axes[0]
    ax.get_legend().set_visible(False)
    sns.despine(left=True, bottom=True)
    f.tight_layout()

    return f
//  [python]
def plot_overall(overall_summary):
    f = plt.figure(figsize=(6, 4))

    for metric, color in [('center', 'pastel'), ('expected', 'muted')]:
        sns.set_color_codes(color)

        x = [res[metric] for model, model_res in overall_summary.items() for task, res in model_res.items()]
        y = [task for model, model_res in overall_summary.items() for task, res in model_res.items()]
        hue = [model for model, model_res in overall_summary.items() for task, res in model_res.items()]

        sns.barplot(x=x, y=y, hue=hue, palette=color, order=[
                    'udalpino-pos', 'udlassy-pos', 'conll2002-ner', 'udlassy-dep', 'sonar-coref', 'udalpino-dep'])

    ax = f.axes[0]
    ax.get_legend().set_visible(False)
    sns.utils.despine(left=True, bottom=True)
    f.tight_layout()

    return f
//  [python]
def plot_accuracies(acc_table, task, agg, color='muted', val_min=1, val_max=0):
    layer_names = ['lex'] + [str(i) for i in range(1, 13)]

    f = plt.figure(figsize=(6, 4))  # ()

    # for agg, color in [('mix', 'muted')]:
    sns.set_color_codes(color)

    keys = sorted([key for key in acc_table.keys() if key[1] == agg])

    x = [name for key in keys for name in layer_names]
    y = [acc_table[key][i] - acc_table[key][i - 1] if i >
         0 else 0 for key in keys for i in range(len(acc_table[key]))]
    hue = [' '.join(key) for key in keys for acc in acc_table[key]]

    if val_min == 1:
        val_min = min([val_min] + y)
    if val_max == 0:
        val_max = max([val_max] + y)

    sns.barplot(x=x, y=y, hue=hue, palette=color)

    ax = f.axes[0]
    ax.legend(ncol=2, loc='upper right', frameon=True)
    ax.set(ylim=(val_min, val_max), ylabel='Accuracy deltas', xlabel='Layer')
    # ax.set_title(task)
    sns.despine(left=True, bottom=True)
    f.tight_layout()
    # plt.show()

    return f
//  [python]
def plot_accuracies(acc_table, task, agg, color='muted', val_min=1, val_max=0):
    layer_names = ['lex'] + [str(i) for i in range(1, 13)]

    f = plt.figure(figsize=(6, 4))  # ()

    # for agg, color in [('mix', 'muted')]:
    sns.set_color_codes(color)

    keys = sorted([key for key in acc_table.keys() if key[1] == agg])

    x = [name for key in keys for name in layer_names]
    y = [acc_table[key][i] - acc_table[key][i - 1] if i >
         0 else 0 for key in keys for i in range(len(acc_table[key]))]
    hue = [' '.join(key) for key in keys for acc in acc_table[key]]

    if val_min == 1:
        val_min = min([val_min] + y)
    if val_max == 0:
        val_max = max([val_max] + y)

    sns.barplot(x=x, y=y, hue=hue, palette=color)

    ax = f.axes[0]
    ax.legend(ncol=2, loc='upper right', frameon=True)
    ax.set(ylim=(val_min, val_max), ylabel='Accuracy deltas', xlabel='Layer')
    # ax.set_title(task)
    sns.utils.despine(left=True, bottom=True)
    f.tight_layout()
    # plt.show()

    return f