jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_change_by_pos(diffs_by_context,plottype='box'):
    fig = plt.figure(figsize=(6,4))
    changes_by_position = {'position':[],'base':[],'diff':[]}
    for lab in diffs_by_context:
        for context in diffs_by_context[lab]:
            for entry in diffs_by_context[lab][context]:
                for pos,diff in enumerate(entry[:-1]):
                    changes_by_position['position'].append(pos+1)
                    changes_by_position['base'].append(lab)
                    changes_by_position['diff'].append(diff)
    dPos = pd.DataFrame(changes_by_position)
    if plottype == 'box':
        sns.boxplot(x="position", y="diff", hue="base", data=dPos, palette=[cols[base],cols[methbase]])
    elif plottype == 'violin':
        sns.violinplot(x="position",y="diff", hue="base", data=dPos, palette=[cols[base],cols[methbase]])
    sns.utils.despine(trim=False)
    plt.xlabel('Adenine Position in 6-mer')
    plt.ylabel('Measured - Expected Current (pA)')
    plt.ylim([-20,20])
    plt.legend(title='',loc='upper center', bbox_to_anchor=(0.5, 1.05),
          ncol=3, fancybox=True)
    plt.savefig('change_by_position_box.pdf',transparent=True,dpi=500, bbox_inches='tight')
//  [python]
def plot_histogram_streetmover(x, args):
    r"""
    Plot histogram of streetmover distance, to better analyze the performance of different models
    
    :param x: streetmover distances
    :param args: parsed arguments
    """
    
    sns.set(color_codes=True, style="white")
    
    sns_plot = sns.distplot(x, bins=int(np.max(x) / 0.002), kde=False)  # kde_kws=dict(bw=0.01))
    sns_plot.set_xticks(np.linspace(0, 0.08, 5))
    sns_plot.set_yticks(np.linspace(0, 10000, 6))
    sns_plot.set_xlim(0, 0.09)
    sns_plot.set_ylim(0, 10000)
    plt.grid(which='major', axis='y', color='gray', linestyle='-', linewidth=1, alpha=.5)
    
    mean = np.mean(x)
    median = np.median(x)
    std = np.std(x)
    plt.axvline(mean, 0, 40, ls='--', c='r', label="mean")
    plt.axvline(median, 0, 40, ls='--', c='g', label="median")
    plt.text(0.088, 4000, f"Mean: {str(mean)[:6]}\nMedian: {str(median)[:6]}\nStd: {str(std)[:6]}", fontsize=20,
                       fontdict=dict(horizontalalignment='right'))
    sns_plot.set_ylabel("N datapoints", fontsize=20)
    sns_plot.set_xlabel("StreetMover distance", fontsize=20)
    sns.despine(ax=sns_plot, left=True, bottom=True)
    # sns_plot.set_title(f"Mean: {str(mean)[:6]}\nMedian: {str(median)[:6]}\nStd: {str(std)[:6]}", fontsize=20,
    #                   fontdict=dict(horizontalalignment='right'))
    sns_plot.legend(prop={'size': 20})
    sns_plot.figure.savefig(f"{args.statistics_path}/{args.file_name}.png", bbox_inches='tight')
//  [python]
def plot_histogram_streetmover(x, args):
    r"""
    Plot histogram of streetmover distance, to better analyze the performance of different models
    
    :param x: streetmover distances
    :param args: parsed arguments
    """
    
    sns.set(color_codes=True, style="white")
    
    sns_plot = sns.distplot(x, bins=int(np.max(x) / 0.002), kde=False)  # kde_kws=dict(bw=0.01))
    sns_plot.set_xticks(np.linspace(0, 0.08, 5))
    sns_plot.set_yticks(np.linspace(0, 10000, 6))
    sns_plot.set_xlim(0, 0.09)
    sns_plot.set_ylim(0, 10000)
    plt.grid(which='major', axis='y', color='gray', linestyle='-', linewidth=1, alpha=.5)
    
    mean = np.mean(x)
    median = np.median(x)
    std = np.std(x)
    plt.axvline(mean, 0, 40, ls='--', c='r', label="mean")
    plt.axvline(median, 0, 40, ls='--', c='g', label="median")
    plt.text(0.088, 4000, f"Mean: {str(mean)[:6]}\nMedian: {str(median)[:6]}\nStd: {str(std)[:6]}", fontsize=20,
                       fontdict=dict(horizontalalignment='right'))
    sns_plot.set_ylabel("N datapoints", fontsize=20)
    sns_plot.set_xlabel("StreetMover distance", fontsize=20)
    sns.utils.despine(ax=sns_plot, left=True, bottom=True)
    # sns_plot.set_title(f"Mean: {str(mean)[:6]}\nMedian: {str(median)[:6]}\nStd: {str(std)[:6]}", fontsize=20,
    #                   fontdict=dict(horizontalalignment='right'))
    sns_plot.legend(prop={'size': 20})
    sns_plot.figure.savefig(f"{args.statistics_path}/{args.file_name}.png", bbox_inches='tight')
//  [python]
def plot_25_multi_pos(df, pos_lst, y_tcks=[0.00, 0.01, 0.02, 0.05]):
    
    df = df[(df.POS.isin(pos_lst)) & (df.EXPERIMENT == 'bulk') &
            (df.CONSIDERED_MAF_TISSUE != 0)]
    sorter(df)
    pos_sorter = dict(zip(pos_lst, range(len(pos_lst))))
    df['POS_SORTER'] = df['POS'].map(pos_sorter)
    df.sort_values('POS_SORTER', inplace=True)
    df['MAF_'] = df.CONSIDERED_MAF_TISSUE**0.5
    
    sns.stripplot(x='CHR_POS_REF_ALT', y='MAF_', hue='LG_SM', data=df,
                  palette=['1.', '0.5', '0.0'], edgecolor='k', linewidth=1)
    
    plt.yticks(ticks=[y**0.5 for y in y_tcks], labels=[str(y) for y in y_tcks])
    plt.xlabel('')
    plt.ylabel('AF (sqrt-t)')
    
    sns.despine(trim=True, offset=5)
    plt.xticks(rotation=45, ha='right')
    
    plt.show()
//  [python]
def plot_25_multi_pos(df, pos_lst, y_tcks=[0.00, 0.01, 0.02, 0.05]):
    
    df = df[(df.POS.isin(pos_lst)) & (df.EXPERIMENT == 'bulk') &
            (df.CONSIDERED_MAF_TISSUE != 0)]
    sorter(df)
    pos_sorter = dict(zip(pos_lst, range(len(pos_lst))))
    df['POS_SORTER'] = df['POS'].map(pos_sorter)
    df.sort_values('POS_SORTER', inplace=True)
    df['MAF_'] = df.CONSIDERED_MAF_TISSUE**0.5
    
    sns.stripplot(x='CHR_POS_REF_ALT', y='MAF_', hue='LG_SM', data=df,
                  palette=['1.', '0.5', '0.0'], edgecolor='k', linewidth=1)
    
    plt.yticks(ticks=[y**0.5 for y in y_tcks], labels=[str(y) for y in y_tcks])
    plt.xlabel('')
    plt.ylabel('AF (sqrt-t)')
    
    sns.utils.despine(trim=True, offset=5)
    plt.xticks(rotation=45, ha='right')
    
    plt.show()
//  [python]
def plot_sml_1tissues(df, y=50):
    '''Plot bars counting the number of variants that are only present in one
    small region.'''
    
    df = df[(df.MAX_MAF_25_BOOL) & (df.SET_CORTEX_ONLY) & (df.SET_ONE_TISSUE) &
            (df.LG_SM == 'Sml')].sort_values(by=['ORGAN_SORTER', 'L_R'])
    
    #to fix the issue with 0bars
    fake = pd.DataFrame(data={'BRAIN_REGION': ['F', 'O'],
                              'L_R': ['R', 'L']})
    
    df = df.append(fake, sort=False).reset_index(drop=True)
    
    sns.countplot(x='BRAIN_REGION', hue='L_R', data=df,
                  order=['PF', 'F', 'P', 'O', 'T'], edgecolor='k')
    
    plt.ylim(0, y)
    plt.ylabel('Number of Variants')
    plt.xlabel('Cortical Lobes')
    plt.title('Remove R-F and L-O!')
    sns.despine(bottom=True, offset=5, trim=True)
    
    plt.show()
//  [python]
def plot_sml_1tissues(df, y=50):
    '''Plot bars counting the number of variants that are only present in one
    small region.'''
    
    df = df[(df.MAX_MAF_25_BOOL) & (df.SET_CORTEX_ONLY) & (df.SET_ONE_TISSUE) &
            (df.LG_SM == 'Sml')].sort_values(by=['ORGAN_SORTER', 'L_R'])
    
    #to fix the issue with 0bars
    fake = pd.DataFrame(data={'BRAIN_REGION': ['F', 'O'],
                              'L_R': ['R', 'L']})
    
    df = df.append(fake, sort=False).reset_index(drop=True)
    
    sns.countplot(x='BRAIN_REGION', hue='L_R', data=df,
                  order=['PF', 'F', 'P', 'O', 'T'], edgecolor='k')
    
    plt.ylim(0, y)
    plt.ylabel('Number of Variants')
    plt.xlabel('Cortical Lobes')
    plt.title('Remove R-F and L-O!')
    sns.utils.despine(bottom=True, offset=5, trim=True)
    
    plt.show()
//  [python]
def plot_number25_vsAF(df):
    
    df = df.copy()
    
    df.fillna(0, inplace=True)
    
    df = df[(df.EXPERIMENT == 'bulk') & (df.CONSIDERED_MAF_25 != 0)]
    
    df['MAF_'] = df.CONSIDERED_MAF_25**0.5
    
    sns.regplot(x='MAF_', y='SUM_POS_25', data=df, color='k',
                scatter_kws={'s':4, 'alpha':0.1}, fit_reg=False)
                #, line_kws={'color':'r'})
    #sns.jointplot('MAF_', 'SUM_POS_25', kind='kde', data=df,
     #             color='r')#.plot_joint(sns.regplot, marker='o', color='k')
    
    plt.xlabel('Allelic Fraction (sqrt-t)')
    plt.xlim(0, 1)
    plt.xticks(ticks=[0., 0.01**0.5, 0.05**0.5, 0.1**0.5, 0.2**0.5, 0.5**0.5,
                      1.0],
               labels=['0.00', '0.01', '0.05', '0.10', '0.20', '0.50', '1.00'])
    
    plt.ylabel('Number of Samples')
    plt.ylim(0, 25)
    plt.yticks(ticks=[0, 5, 10, 15, 20, 25])
    
    sns.despine(offset=5, trim=True)
    
    plt.show()
//  [python]
def plot_number25_vsAF(df):
    
    df = df.copy()
    
    df.fillna(0, inplace=True)
    
    df = df[(df.EXPERIMENT == 'bulk') & (df.CONSIDERED_MAF_25 != 0)]
    
    df['MAF_'] = df.CONSIDERED_MAF_25**0.5
    
    sns.regplot(x='MAF_', y='SUM_POS_25', data=df, color='k',
                scatter_kws={'s':4, 'alpha':0.1}, fit_reg=False)
                #, line_kws={'color':'r'})
    #sns.jointplot('MAF_', 'SUM_POS_25', kind='kde', data=df,
     #             color='r')#.plot_joint(sns.regplot, marker='o', color='k')
    
    plt.xlabel('Allelic Fraction (sqrt-t)')
    plt.xlim(0, 1)
    plt.xticks(ticks=[0., 0.01**0.5, 0.05**0.5, 0.1**0.5, 0.2**0.5, 0.5**0.5,
                      1.0],
               labels=['0.00', '0.01', '0.05', '0.10', '0.20', '0.50', '1.00'])
    
    plt.ylabel('Number of Samples')
    plt.ylim(0, 25)
    plt.yticks(ticks=[0, 5, 10, 15, 20, 25])
    
    sns.utils.despine(offset=5, trim=True)
    
    plt.show()
//  [python]
def show_fig(std, ax, title):
    """Create a plot of normally distributed data in a given axis"""
    
    for ii in range(3):
        data = stats.norm(centers[ii], std).rvs(numData)
        offset = ii*numData
        ax.plot( offset+np.arange(numData), data, '.', ms=10)
        
    ax.xaxis.set_ticks([50,150,250])
    ax.set_xticklabels(['Group1', 'Group2', 'Group3'])
    ax.set_title(title)
    sns.despine()
//  [python]
def show_fig(std, ax, title):
    """Create a plot of normally distributed data in a given axis"""
    
    for ii in range(3):
        data = stats.norm(centers[ii], std).rvs(numData)
        offset = ii*numData
        ax.plot( offset+np.arange(numData), data, '.', ms=10)
        
    ax.xaxis.set_ticks([50,150,250])
    ax.set_xticklabels(['Group1', 'Group2', 'Group3'])
    ax.set_title(title)
    sns.utils.despine()
//  [python]
def plot_nodes_by_tsne(xs, ys, args=None, extension="png"):
    x_embed = TSNE(n_components=2).fit_transform(xs)

    df = pd.DataFrame({
        "x_coord": x_embed[:, 0],
        "y_coord": x_embed[:, 1],
        "class": ys,
    })
    plot = sns.scatterplot(x="x_coord", y="y_coord", hue="class", data=df,
                           legend=False, palette="Set1")
    plot.set_xlabel("")
    plot.set_ylabel("")
    plot.get_xaxis().set_visible(False)
    plot.get_yaxis().set_visible(False)
    sns.despine(left=False, right=False, bottom=False, top=False)

    key, path = _get_key_and_makedirs(args, base_path="../figs")
    plot.get_figure().savefig("{}/fig_tsne_{}.{}".format(path, key, extension), bbox_inches='tight')
    plt.clf()
//  [python]
def plot_nodes_by_tsne(xs, ys, args=None, extension="png"):
    x_embed = TSNE(n_components=2).fit_transform(xs)

    df = pd.DataFrame({
        "x_coord": x_embed[:, 0],
        "y_coord": x_embed[:, 1],
        "class": ys,
    })
    plot = sns.scatterplot(x="x_coord", y="y_coord", hue="class", data=df,
                           legend=False, palette="Set1")
    plot.set_xlabel("")
    plot.set_ylabel("")
    plot.get_xaxis().set_visible(False)
    plot.get_yaxis().set_visible(False)
    sns.utils.despine(left=False, right=False, bottom=False, top=False)

    key, path = _get_key_and_makedirs(args, base_path="../figs")
    plot.get_figure().savefig("{}/fig_tsne_{}.{}".format(path, key, extension), bbox_inches='tight')
    plt.clf()
//  [python]
def make_AF_plot_variant_tissues(df, POS):
    '''take the position and plot AF in all tissues for this position in boxes
    that are graded by AF level.'''
    
    #initialize data
    
    #needed b/c of incomplete list of tissues
    if len(df.SORTER.unique()) != 25:
    
        pos = df[df.POS == POS][['MAF', 'SORTER']]
        flag = df[df.POS == POS][['CHR_POS_REF_ALT', 'FLAG_NOISE', 'SORTER']]
    
        pos.sort_values(by='SORTER', inplace=True)
    
        dummy = pd.DataFrame(data=[i for i in range(25)], columns=['SORTER'])
        dummy['MAF'] = 0
        pos = pos.append(dummy, sort=True).groupby('SORTER').sum()\
                                                            .reset_index()
        
        pos = pd.merge(pos, flag, how='left')
        pos.fillna('ZONK', inplace=True)
    
    else:
        
        pos = df[df.POS == POS][['CHR_POS_REF_ALT', 'MAF', 'SORTER',
                                 'FLAG_NOISE']]
        pos.sort_values(by='SORTER', inplace=True)
    
    #make color list
    
    colors = make_colors(pos)
    
    #make boxes
    
    fig,ax = plt.subplots(1)

    boxes = make_tissues()
        
    pc = PatchCollection(boxes, facecolor=colors, edgecolor='k')
    ax.add_collection(pc)
    
    ax.plot()
    sns.despine(left=True, bottom=True)
    plt.tick_params(bottom=False, left=False,
                    labelbottom=False, labelleft=False)
    plt.xlim(-40, 40)
    plt.ylim(-1, 59)
    
    plt.title(pos.CHR_POS_REF_ALT.unique()[0])

    plt.show()
//  [python]
def make_AF_plot_variant_tissues(df, POS):
    '''take the position and plot AF in all tissues for this position in boxes
    that are graded by AF level.'''
    
    #initialize data
    
    #needed b/c of incomplete list of tissues
    if len(df.SORTER.unique()) != 25:
    
        pos = df[df.POS == POS][['MAF', 'SORTER']]
        flag = df[df.POS == POS][['CHR_POS_REF_ALT', 'FLAG_NOISE', 'SORTER']]
    
        pos.sort_values(by='SORTER', inplace=True)
    
        dummy = pd.DataFrame(data=[i for i in range(25)], columns=['SORTER'])
        dummy['MAF'] = 0
        pos = pos.append(dummy, sort=True).groupby('SORTER').sum()\
                                                            .reset_index()
        
        pos = pd.merge(pos, flag, how='left')
        pos.fillna('ZONK', inplace=True)
    
    else:
        
        pos = df[df.POS == POS][['CHR_POS_REF_ALT', 'MAF', 'SORTER',
                                 'FLAG_NOISE']]
        pos.sort_values(by='SORTER', inplace=True)
    
    #make color list
    
    colors = make_colors(pos)
    
    #make boxes
    
    fig,ax = plt.subplots(1)

    boxes = make_tissues()
        
    pc = PatchCollection(boxes, facecolor=colors, edgecolor='k')
    ax.add_collection(pc)
    
    ax.plot()
    sns.utils.despine(left=True, bottom=True)
    plt.tick_params(bottom=False, left=False,
                    labelbottom=False, labelleft=False)
    plt.xlim(-40, 40)
    plt.ylim(-1, 59)
    
    plt.title(pos.CHR_POS_REF_ALT.unique()[0])

    plt.show()
//  [python]
sns.set_context("notebook")

for track in read_gpx_file("example1.gpx"):
    for i, segment in enumerate(track["segments"]):
        fig, ax1 = plt.subplots(constrained_layout=True)
        ax1.plot(segment["time"], segment["distance"] / 1000.0, lw=5)
        ax1.set(xlabel="Time", ylabel="Distance / km")
        ax1.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
        sns.despine(fig=fig)
//  [python]
sns.set_context("notebook")

for track in read_gpx_file("example1.gpx"):
    for i, segment in enumerate(track["segments"]):
        fig, ax1 = plt.subplots(constrained_layout=True)
        ax1.plot(segment["time"], segment["distance"] / 1000.0, lw=5)
        ax1.set(xlabel="Time", ylabel="Distance / km")
        ax1.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
        sns.utils.despine(fig=fig)
//  [python]
sns.set_context("notebook")

for track in read_gpx_file("example1.gpx"):
    for i, segment in enumerate(track["segments"]):
        # Plot elevation as function of distance:
        fig, _ = plot_filled(
            track,
            segment,
            xvar="Distance / km",
            yvar="elevation",
            zvar="Velocity / km/h",
        )
        sns.despine(fig=fig)
//  [python]
sns.set_context("notebook")

for track in read_gpx_file("example1.gpx"):
    for i, segment in enumerate(track["segments"]):
        # Plot elevation as function of distance:
        fig, _ = plot_filled(
            track,
            segment,
            xvar="Distance / km",
            yvar="elevation",
            zvar="Velocity / km/h",
        )
        sns.utils.despine(fig=fig)
//  [python]
plots = {"V_D": [], "V_R": [], "Q_D": [], "Q_R": []}
for item in plots:
    fig, axs = plt.subplots(1, 3, figsize=(4, 1.6), dpi=300)
    plots[item] = [fig, axs]

for flag_id, flag in enumerate(["red", "yellow", "noflag"]):
    for v in ["V_D", "V_R", "Q_D", "Q_R"]:
        bar_plot_batch(bokeh["nonsurvivors"][v][flag], bokeh["survivors"][v][flag], bokeh["time"], plots[v][1][flag_id], v + " " + flag)

for item in plots:
    plots[item][0].tight_layout()
    seaborn.despine(plots[item][0])
    plots[item][0].savefig(os.path.join(pf, item + ".pdf"))
//  [python]
plots = {"V_D": [], "V_R": [], "Q_D": [], "Q_R": []}
for item in plots:
    fig, axs = plt.subplots(1, 3, figsize=(4, 1.6), dpi=300)
    plots[item] = [fig, axs]

for flag_id, flag in enumerate(["red", "yellow", "noflag"]):
    for v in ["V_D", "V_R", "Q_D", "Q_R"]:
        bar_plot_batch(bokeh["nonsurvivors"][v][flag], bokeh["survivors"][v][flag], bokeh["time"], plots[v][1][flag_id], v + " " + flag)

for item in plots:
    plots[item][0].tight_layout()
    seaborn.utils.despine(plots[item][0])
    plots[item][0].savefig(os.path.join(pf, item + ".pdf"))
//  [python]
def _make(
        self,
        **kwargs: ty.Any,
    ) -> tuple[Figure, Axes]:
        sns.violinplot(
            [v.values for v in self.attribute_metric_map.values()],
            ax=self.ax,
            palette="Set3",
        )
        mean_perf = []
        median_perf = []
        best_perf = []
        for vals in self.attribute_metric_map.values():
            # top performance marker
            obj_fn = self.metrics_obj_fn
            best_perf.append(self._sort_vals_obj(vals, obj_fn)[0])
            mean_perf.append(np.mean(vals))
            median_perf.append(np.median(vals))

        labels = [
            f"Mean: {mean:.2e}\nBest: {best:.2e}\n{name}"
            for mean, best, name in zip(
                mean_perf, best_perf, self.attribute_metric_map.keys()
            )
        ]
        self.ax.set_xticks(
            np.arange(len(self.attribute_metric_map)),
            labels=labels,
        )

        sns.despine(left=True, bottom=True)
        return self.figure, self.ax
//  [python]
def _make(
        self,
        **kwargs: ty.Any,
    ) -> tuple[Figure, Axes]:
        sns.violinplot(
            [v.values for v in self.attribute_metric_map.values()],
            ax=self.ax,
            palette="Set3",
        )
        mean_perf = []
        median_perf = []
        best_perf = []
        for vals in self.attribute_metric_map.values():
            # top performance marker
            obj_fn = self.metrics_obj_fn
            best_perf.append(self._sort_vals_obj(vals, obj_fn)[0])
            mean_perf.append(np.mean(vals))
            median_perf.append(np.median(vals))

        labels = [
            f"Mean: {mean:.2e}\nBest: {best:.2e}\n{name}"
            for mean, best, name in zip(
                mean_perf, best_perf, self.attribute_metric_map.keys()
            )
        ]
        self.ax.set_xticks(
            np.arange(len(self.attribute_metric_map)),
            labels=labels,
        )

        sns.utils.despine(left=True, bottom=True)
        return self.figure, self.ax
//  [python]
def task_create_convergence_gif(produces, algorithm):
    start_x = np.array([2])
    hessian = example_hessian if algorithm == "trust-ncg" else NotImplementedError
    res = minimize_with_history(
        example_criterion, start_x, method=algorithm, jac=example_gradient, hess=hessian
    )

    # repeat the last point to show it longer in the gif
    points = res.history + [res.history[-1]] * 2

    @gif.frame
    def _plot_history(points):
        fig, ax = plot_function()
        sns.rugplot(points, ax=ax)
        plt.plot(
            points[-1],
            example_criterion(points[-1]),
            marker="*",
        )
        sns.despine()

    frames = [_plot_history[: i + 1] for i in range(len(points))]

    gif.save(frames, produces, duration=2.5, unit="s")
//  [python]
def task_create_convergence_gif(produces, algorithm):
    start_x = np.array([2])
    hessian = example_hessian if algorithm == "trust-ncg" else NotImplementedError
    res = minimize_with_history(
        example_criterion, start_x, method=algorithm, jac=example_gradient, hess=hessian
    )

    # repeat the last point to show it longer in the gif
    points = res.history + [res.history[-1]] * 2

    @gif.frame
    def _plot_history(points):
        fig, ax = plot_function()
        sns.rugplot(points, ax=ax)
        plt.plot(
            points[-1],
            example_criterion(points[-1]),
            marker="*",
        )
        sns.utils.despine()

    frames = [_plot_history[: i + 1] for i in range(len(points))]

    gif.save(frames, produces, duration=2.5, unit="s")
//  [python]
def plot_2d_pareto(trajectories: dict, scale):
    """Adaptation of code from: https://github.com/Cranial-XIX/CAGrad"""
    fig, ax = plt.subplots(figsize=(5, 5))

    F = Toy(scale=scale)

    losses = []
    for res in trajectories.values():
        losses.append(F.batch_forward(torch.from_numpy(res["traj"])))

    yy = -8.3552
    x = np.linspace(-7, 7, 1000)

    inpt = np.stack((x, [yy] * len(x))).T
    Xs = torch.from_numpy(inpt).double()

    Ys = F.batch_forward(Xs)
    ax.plot(
        Ys.numpy()[:, 0],
        Ys.numpy()[:, 1],
        "-",
        linewidth=8,
        color="#72727A",
        #label="Pareto Front",
    )  # Pareto front

    for i, tt in enumerate(losses):
        ax.scatter(
            tt[0, 0],
            tt[0, 1],
            color="k",
            s=150,
            zorder=10,
            #label="Initial Point" if i == 0 else None,
        )
        colors = matplotlib.cm.magma_r(np.linspace(0.1, 0.6, tt.shape[0]))
        ax.scatter(tt[:, 0], tt[:, 1], color=colors, s=5, zorder=9)

    sns.despine()
    #ax.set_xlabel(r"$\ell_1$", size=30)
    #ax.set_ylabel(r"$\ell_2$", size=30)
    ax.xaxis.set_label_coords(1.015, -0.03)
    ax.yaxis.set_label_coords(-0.01, 1.01)

    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(20)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(20)

    legend = ax.legend(
        loc=2, bbox_to_anchor=(-0.15, 1.3), frameon=False, fontsize=20, ncol=2
    )
    return ax, fig, legend
//  [python]
def plot_2d_pareto(trajectories: dict, scale):
    """Adaptation of code from: https://github.com/Cranial-XIX/CAGrad"""
    fig, ax = plt.subplots(figsize=(5, 5))

    F = Toy(scale=scale)

    losses = []
    for res in trajectories.values():
        losses.append(F.batch_forward(torch.from_numpy(res["traj"])))

    yy = -8.3552
    x = np.linspace(-7, 7, 1000)

    inpt = np.stack((x, [yy] * len(x))).T
    Xs = torch.from_numpy(inpt).double()

    Ys = F.batch_forward(Xs)
    ax.plot(
        Ys.numpy()[:, 0],
        Ys.numpy()[:, 1],
        "-",
        linewidth=8,
        color="#72727A",
        #label="Pareto Front",
    )  # Pareto front

    for i, tt in enumerate(losses):
        ax.scatter(
            tt[0, 0],
            tt[0, 1],
            color="k",
            s=150,
            zorder=10,
            #label="Initial Point" if i == 0 else None,
        )
        colors = matplotlib.cm.magma_r(np.linspace(0.1, 0.6, tt.shape[0]))
        ax.scatter(tt[:, 0], tt[:, 1], color=colors, s=5, zorder=9)

    sns.utils.despine()
    #ax.set_xlabel(r"$\ell_1$", size=30)
    #ax.set_ylabel(r"$\ell_2$", size=30)
    ax.xaxis.set_label_coords(1.015, -0.03)
    ax.yaxis.set_label_coords(-0.01, 1.01)

    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(20)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(20)

    legend = ax.legend(
        loc=2, bbox_to_anchor=(-0.15, 1.3), frameon=False, fontsize=20, ncol=2
    )
    return ax, fig, legend
//  [python]
sns.stripplot(data=simulation_df, x="Data Quality", y="HF-HRV (n.u.)",
              size=8, color=".3", linewidth=0)
plt.axhline(y=initial_hf, linestyle="--", color="gray")
plt.title("HF-HV recovery \n after RR artefacts correction")
plt.annotate("True HF-HRV", xy=(0, initial_hf), xytext=(-0.4, initial_hf - 0.05),
             arrowprops = dict(facecolor ='grey', shrink = 0.05))
sns.despine()
//  [python]
sns.stripplot(data=simulation_df, x="Data Quality", y="HF-HRV (n.u.)",
              size=8, color=".3", linewidth=0)
plt.axhline(y=initial_hf, linestyle="--", color="gray")
plt.title("HF-HV recovery \n after RR artefacts correction")
plt.annotate("True HF-HRV", xy=(0, initial_hf), xytext=(-0.4, initial_hf - 0.05),
             arrowprops = dict(facecolor ='grey', shrink = 0.05))
sns.utils.despine()
//  [python]
def Bars():
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    sns.set_theme(style="white", context="talk")
    rs = np.random.RandomState(8)

    # Set up the matplotlib figure
    f, (ax1, ax2, ax3, ax4) = plt.subplots(1,4, figsize=(10,3), sharex=True)

    # Generate some sequential data
    x = np.array(list("ABCDEFGHIJ"))
    y1 = np.arange(1, 11)
    sns.barplot(x=x, y=y1, palette="rocket", ax=ax1)
    ax1.axhline(0, color="k", clip_on=False)
    ax1.set_ylabel("Sequential")

    # Center the data to make it diverging
    y2 = y1 - 5.5
    sns.barplot(x=x, y=y2, palette="vlag", ax=ax2)
    ax2.axhline(0, color="k", clip_on=False)
    ax2.set_ylabel("Diverging")

    # Randomly reorder the data to make it qualitative
    y3 = rs.choice(y1, len(y1), replace=False)
    sns.barplot(x=x, y=y3, palette="deep", ax=ax3)
    ax3.axhline(0, color="k", clip_on=False)
    ax3.set_ylabel("Qualitative")

    # Finalize the plot
    sns.despine(bottom=True)
    plt.setp(f.axes, yticks=[])
    plt.tight_layout(h_pad=2)
//  [python]
def Bars():
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    sns.set_theme(style="white", context="talk")
    rs = np.random.RandomState(8)

    # Set up the matplotlib figure
    f, (ax1, ax2, ax3, ax4) = plt.subplots(1,4, figsize=(10,3), sharex=True)

    # Generate some sequential data
    x = np.array(list("ABCDEFGHIJ"))
    y1 = np.arange(1, 11)
    sns.barplot(x=x, y=y1, palette="rocket", ax=ax1)
    ax1.axhline(0, color="k", clip_on=False)
    ax1.set_ylabel("Sequential")

    # Center the data to make it diverging
    y2 = y1 - 5.5
    sns.barplot(x=x, y=y2, palette="vlag", ax=ax2)
    ax2.axhline(0, color="k", clip_on=False)
    ax2.set_ylabel("Diverging")

    # Randomly reorder the data to make it qualitative
    y3 = rs.choice(y1, len(y1), replace=False)
    sns.barplot(x=x, y=y3, palette="deep", ax=ax3)
    ax3.axhline(0, color="k", clip_on=False)
    ax3.set_ylabel("Qualitative")

    # Finalize the plot
    sns.utils.despine(bottom=True)
    plt.setp(f.axes, yticks=[])
    plt.tight_layout(h_pad=2)
//  [python]
def make_stripplot(fn):
    """
    Makes stripplot of runtime for different spatial null models

    Parameters
    ----------
    fn : {'cached.csv', 'uncached.csv'}
        Filename to load runtime data from

    Returns
    -------
    ax : matplotlib.pyplot.Axes
        Axis with plot
    """
    data = pd.read_csv(DATADIR / fn)
    fig, ax = plt.subplots(1, 1)
    ax = sns.stripplot(x='runtime', y='spatnull', hue='parcellation',
                       order=SPATNULLS, hue_order=ORDER, dodge=True, ax=ax,
                       data=data, palette=PARCHUES)
    ax.set_xscale('log')
    xl = (10**-3, 10**5)
    ax.hlines(np.arange(0.5, 9.5), *xl, linestyle='dashed', linewidth=0.5,
              color=np.array([50, 50, 50]) / 255)
    ax.set(xlim=xl, ylim=(9.5, -0.5))
    yticklabels = ax.get_yticklabels()
    for n, ytick in enumerate(yticklabels):
        ytick.set_color(SPATHUES[n])
    ax.set_yticklabels(yticklabels)
    ax.legend_.set_visible(False)
    sns.despine(ax=ax)

    return ax
//  [python]
def make_stripplot(fn):
    """
    Makes stripplot of runtime for different spatial null models

    Parameters
    ----------
    fn : {'cached.csv', 'uncached.csv'}
        Filename to load runtime data from

    Returns
    -------
    ax : matplotlib.pyplot.Axes
        Axis with plot
    """
    data = pd.read_csv(DATADIR / fn)
    fig, ax = plt.subplots(1, 1)
    ax = sns.stripplot(x='runtime', y='spatnull', hue='parcellation',
                       order=SPATNULLS, hue_order=ORDER, dodge=True, ax=ax,
                       data=data, palette=PARCHUES)
    ax.set_xscale('log')
    xl = (10**-3, 10**5)
    ax.hlines(np.arange(0.5, 9.5), *xl, linestyle='dashed', linewidth=0.5,
              color=np.array([50, 50, 50]) / 255)
    ax.set(xlim=xl, ylim=(9.5, -0.5))
    yticklabels = ax.get_yticklabels()
    for n, ytick in enumerate(yticklabels):
        ytick.set_color(SPATHUES[n])
    ax.set_yticklabels(yticklabels)
    ax.legend_.set_visible(False)
    sns.utils.despine(ax=ax)

    return ax
//  [python]
def make_violins(df, x='method', y='rank', save=None, show=True):
    ax = sns.violinplot(x=x, y=y, data=df, color='0.8', bw=.1)
    for artist in ax.lines:
        artist.set_zorder(10)
    for artist in ax.findobj(PathCollection):
        artist.set_zorder(11)
    sns.stripplot(data=df, x=x, y=y, jitter=True, s=1, alpha=0.5)
    sns.despine()
    plt.ylim(-14, -3)
    plt.xlabel('Samples')
    plt.ylabel('Docking scores')
    if not save is None:
        plt.savefig(save, format="pdf")
    if show:
        plt.show()

    pass
//  [python]
def make_violins(df, x='method', y='rank', save=None, show=True):
    ax = sns.violinplot(x=x, y=y, data=df, color='0.8', bw=.1)
    for artist in ax.lines:
        artist.set_zorder(10)
    for artist in ax.findobj(PathCollection):
        artist.set_zorder(11)
    sns.stripplot(data=df, x=x, y=y, jitter=True, s=1, alpha=0.5)
    sns.utils.despine()
    plt.ylim(-14, -3)
    plt.xlabel('Samples')
    plt.ylabel('Docking scores')
    if not save is None:
        plt.savefig(save, format="pdf")
    if show:
        plt.show()

    pass
//  [python]
def downstream_plot_performance(df):
    print("Plotting...")
    sns.set_theme(style="whitegrid")
    f, ax = plt.subplots()
    sns.despine(bottom=True, left=True)

    xtitle = 'Normalized Performance Metric'

    df = pd.melt(df, ['Model', 'Dataset'], value_vars='metric', value_name=xtitle)
    sns.stripplot(x=xtitle, y="Dataset", hue="Model", data=df, dodge=True, alpha=.25, zorder=1, size=2)
    sns.pointplot(x=xtitle, y="Dataset", hue="Model", data=df, dodge=0.65, join=False,
                  palette="pastel", errwidth=1, markers="d", scale=0.5)
    handles, labels = ax.get_legend_handles_labels()
    ax.legend([handles[labels.index(l) + len(LEGEND_ORDER)] for i, l in enumerate(LEGEND_ORDER)],
              ["({}.) {}".format(i+1, l) for i, l in enumerate(LEGEND_ORDER)], title="Models",
              handletextpad=0, columnspacing=1, fontsize='x-small', loc="best", ncol=1, frameon=True)
    plt.title("Performance Metrics as Multiple of Chance-level By Dataset and Model")
    plt.show()
    print("Done.")
//  [python]
def downstream_plot_performance(df):
    print("Plotting...")
    sns.set_theme(style="whitegrid")
    f, ax = plt.subplots()
    sns.utils.despine(bottom=True, left=True)

    xtitle = 'Normalized Performance Metric'

    df = pd.melt(df, ['Model', 'Dataset'], value_vars='metric', value_name=xtitle)
    sns.stripplot(x=xtitle, y="Dataset", hue="Model", data=df, dodge=True, alpha=.25, zorder=1, size=2)
    sns.pointplot(x=xtitle, y="Dataset", hue="Model", data=df, dodge=0.65, join=False,
                  palette="pastel", errwidth=1, markers="d", scale=0.5)
    handles, labels = ax.get_legend_handles_labels()
    ax.legend([handles[labels.index(l) + len(LEGEND_ORDER)] for i, l in enumerate(LEGEND_ORDER)],
              ["({}.) {}".format(i+1, l) for i, l in enumerate(LEGEND_ORDER)], title="Models",
              handletextpad=0, columnspacing=1, fontsize='x-small', loc="best", ncol=1, frameon=True)
    plt.title("Performance Metrics as Multiple of Chance-level By Dataset and Model")
    plt.show()
    print("Done.")
//  [python]
def plot_time_corrs(subjects, axes):

    x = np.arange(1, 5)
    palette = [".2", ".5"]

    for subj, ax in zip(subjects, axes):

        res_fname = "correlation_analysis/{}_rest_ifs.pkz".format(subj)
        res = moss.load_pkl(res_fname)

        for line, color in zip(res.corr_times.T, palette):
            ax.plot(x, line, "o-", color=color, ms=3, clip_on=False)

        sig = res.corr_times_pctiles > 95
        ax.plot(x[sig], np.ones(sig.sum()) * .0025,
                marker=(6, 2, 0), ls="", mew=.35, mec=".2", ms=3)

        ax.set(xticks=x, xlim=(.6, 4.4), ylim=(0, .07))
        sns.despine(ax=ax, trim=True)

    plt.setp(axes[1:], yticklabels=[])
    axes[0].set_ylabel("Correlation (r)")
//  [python]
def plot_time_corrs(subjects, axes):

    x = np.arange(1, 5)
    palette = [".2", ".5"]

    for subj, ax in zip(subjects, axes):

        res_fname = "correlation_analysis/{}_rest_ifs.pkz".format(subj)
        res = moss.load_pkl(res_fname)

        for line, color in zip(res.corr_times.T, palette):
            ax.plot(x, line, "o-", color=color, ms=3, clip_on=False)

        sig = res.corr_times_pctiles > 95
        ax.plot(x[sig], np.ones(sig.sum()) * .0025,
                marker=(6, 2, 0), ls="", mew=.35, mec=".2", ms=3)

        ax.set(xticks=x, xlim=(.6, 4.4), ylim=(0, .07))
        sns.utils.despine(ax=ax, trim=True)

    plt.setp(axes[1:], yticklabels=[])
    axes[0].set_ylabel("Correlation (r)")
//  [python]
def mosaic_number_per_individual(df, y=500):
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['INDIVIDUAL', 'MOSAIC_CLASS_SSS'])
    
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors)
    plt.ylim(0,y)
    sns.despine(bottom=True, offset=5, trim=True)
    plt.ylabel('Number of Mosaic Variants')

    plt.show()
//  [python]
def mosaic_number_per_individual(df, y=500):
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['INDIVIDUAL', 'MOSAIC_CLASS_SSS'])
    
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors)
    plt.ylim(0,y)
    sns.utils.despine(bottom=True, offset=5, trim=True)
    plt.ylabel('Number of Mosaic Variants')

    plt.show()
//  [python]
def plot_with_custum_ci_SP_highnumber(df, category='SPERM_A'):
    
    '''use category as defined by the _XXX. e.g. SPERM_A'''
    
    df = df.sort_values(by=['MAF_' + category], ascending=False)
    df = df.reset_index(drop=True).reset_index()
    plt.plot((df.iloc[:,0] + 1), df['MAF_' + category], color='g')
    plt.plot((df.iloc[:,0] + 1), df['UPPER_CI_' + category], color='0.5')
    plt.plot((df.iloc[:,0] + 1), df['LOWER_CI_' + category], color='0.5')
    plt.xlabel('Ranked Mosaic Variants')
    plt.ylabel('Allelic Fraction (Sperm)')
    #plt.xlim(0,70)
    #plt.ylim(0,0.25)
    sns.despine(offset=5, trim=True)
    plt.show()
//  [python]
def plot_with_custum_ci_SP_highnumber(df, category='SPERM_A'):
    
    '''use category as defined by the _XXX. e.g. SPERM_A'''
    
    df = df.sort_values(by=['MAF_' + category], ascending=False)
    df = df.reset_index(drop=True).reset_index()
    plt.plot((df.iloc[:,0] + 1), df['MAF_' + category], color='g')
    plt.plot((df.iloc[:,0] + 1), df['UPPER_CI_' + category], color='0.5')
    plt.plot((df.iloc[:,0] + 1), df['LOWER_CI_' + category], color='0.5')
    plt.xlabel('Ranked Mosaic Variants')
    plt.ylabel('Allelic Fraction (Sperm)')
    #plt.xlim(0,70)
    #plt.ylim(0,0.25)
    sns.utils.despine(offset=5, trim=True)
    plt.show()
//  [python]
def plot_variable_importance(df_variable_importance: pd.DataFrame,
                             title: str=None,
                             dim: tuple=(12, 8),
                             path: str=None):
    """Plot variable importance of a given model.

    Parameters
    ----------
    df_variable_importance : pd.DataFrame
        DataFrame containing columns "predictor" and "importance".
    title : str, optional
        Title of the plot.
    dim : tuple, optional
        Width and length of the plot.
    path : str, optional
        Path to store the figure.
    """
    with plt.style.context("seaborn-ticks"):
        fig, ax = plt.subplots(figsize=dim)
        ax = sns.barplot(x="importance", y="predictor",
                         data=df_variable_importance,
                         color="cornflowerblue")
        if title:
            ax.set_title(title, fontsize=20)
        else:
            ax.set_title("Variable importance", fontsize=20)

        # Make pretty axis
        sns.despine(ax=ax, right=True)
        plt.ylabel('Predictor', fontsize=15)
        plt.xlabel('Importance', fontsize=15)

        # Remove white lines from the second axis
        ax.grid(False)

        if path is not None:
            plt.savefig(path, format="png", dpi=300, bbox_inches="tight")

        plt.show()
//  [python]
def plot_variable_importance(df_variable_importance: pd.DataFrame,
                             title: str=None,
                             dim: tuple=(12, 8),
                             path: str=None):
    """Plot variable importance of a given model.

    Parameters
    ----------
    df_variable_importance : pd.DataFrame
        DataFrame containing columns "predictor" and "importance".
    title : str, optional
        Title of the plot.
    dim : tuple, optional
        Width and length of the plot.
    path : str, optional
        Path to store the figure.
    """
    with plt.style.context("seaborn-ticks"):
        fig, ax = plt.subplots(figsize=dim)
        ax = sns.barplot(x="importance", y="predictor",
                         data=df_variable_importance,
                         color="cornflowerblue")
        if title:
            ax.set_title(title, fontsize=20)
        else:
            ax.set_title("Variable importance", fontsize=20)

        # Make pretty axis
        sns.utils.despine(ax=ax, right=True)
        plt.ylabel('Predictor', fontsize=15)
        plt.xlabel('Importance', fontsize=15)

        # Remove white lines from the second axis
        ax.grid(False)

        if path is not None:
            plt.savefig(path, format="png", dpi=300, bbox_inches="tight")

        plt.show()
//  [python]
def mosaic_number_per_cohort(df, y=500):
    '''used for cohort-specific plot by only feeding one cohort at a time.'''
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['COHORT', 'MOSAIC_CLASS_SSS'])
    
    sns.countplot(x='COHORT', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors)
    
    plt.ylim(0,y)
    sns.despine(bottom=True, offset=5, trim=True)
    plt.ylabel('Number of Mosaic Variants')

    plt.show()
//  [python]
def mosaic_number_per_cohort(df, y=500):
    '''used for cohort-specific plot by only feeding one cohort at a time.'''
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['COHORT', 'MOSAIC_CLASS_SSS'])
    
    sns.countplot(x='COHORT', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors)
    
    plt.ylim(0,y)
    sns.utils.despine(bottom=True, offset=5, trim=True)
    plt.ylabel('Number of Mosaic Variants')

    plt.show()
//  [python]
def plot_univariate_predictor_quality(df_metric: pd.DataFrame,
                                      dim: tuple=(12, 8),
                                      path: str=None):
    """Plot univariate quality of the predictors.

    Parameters
    ----------
    df_metric : pd.DatFrame
        DataFrame containing for each variable the train AUC or RMSE and
        test AUC or RMSE along with a boolean indicating whether or not it is selected
        based on the criteria.
    dim : tuple, optional
        Width and length of the plot.
    path : str, optional
        Path to store the figure.
    """

    if "AUC selection" in df_metric.columns:
        metric = "AUC"
        ascending = False
    elif "RMSE selection" in df_metric.columns:
        metric = "RMSE"
        ascending = True

    df = (df_metric[df_metric["preselection"]]
          .sort_values(by=metric+" selection", ascending=ascending))

    df = pd.melt(df, id_vars=["predictor"],
                 value_vars=[metric+" train", metric+" selection"],
                 var_name="split",
                 value_name=metric)

    # plot data
    with plt.style.context("seaborn-ticks"):
        fig, ax = plt.subplots(figsize=dim)

        ax = sns.barplot(x=metric, y="predictor", hue="split", data=df)
        ax.set_title("Univariate predictor quality", fontsize=20)

        # Set pretty axis
        sns.despine(ax=ax, right=True)
        plt.ylabel("Predictor", fontsize=15)
        plt.xlabel(metric, fontsize=15)

        # Remove white lines from the second axis
        ax.grid(False)

        if path is not None:
            plt.savefig(path, format="png", dpi=300, bbox_inches="tight")

        plt.gca().legend().set_title("")

        plt.show()
//  [python]
def plot_univariate_predictor_quality(df_metric: pd.DataFrame,
                                      dim: tuple=(12, 8),
                                      path: str=None):
    """Plot univariate quality of the predictors.

    Parameters
    ----------
    df_metric : pd.DatFrame
        DataFrame containing for each variable the train AUC or RMSE and
        test AUC or RMSE along with a boolean indicating whether or not it is selected
        based on the criteria.
    dim : tuple, optional
        Width and length of the plot.
    path : str, optional
        Path to store the figure.
    """

    if "AUC selection" in df_metric.columns:
        metric = "AUC"
        ascending = False
    elif "RMSE selection" in df_metric.columns:
        metric = "RMSE"
        ascending = True

    df = (df_metric[df_metric["preselection"]]
          .sort_values(by=metric+" selection", ascending=ascending))

    df = pd.melt(df, id_vars=["predictor"],
                 value_vars=[metric+" train", metric+" selection"],
                 var_name="split",
                 value_name=metric)

    # plot data
    with plt.style.context("seaborn-ticks"):
        fig, ax = plt.subplots(figsize=dim)

        ax = sns.barplot(x=metric, y="predictor", hue="split", data=df)
        ax.set_title("Univariate predictor quality", fontsize=20)

        # Set pretty axis
        sns.utils.despine(ax=ax, right=True)
        plt.ylabel("Predictor", fontsize=15)
        plt.xlabel(metric, fontsize=15)

        # Remove white lines from the second axis
        ax.grid(False)

        if path is not None:
            plt.savefig(path, format="png", dpi=300, bbox_inches="tight")

        plt.gca().legend().set_title("")

        plt.show()
//  [python]
def mosaic_number_per_individual_broken_axis(df):
    
    colors = ['g', 'xkcd:brown', 'xkcd:bright orange']
    
    df = df.sort_values(by=['INDIVIDUAL', 'MOSAIC_CLASS_SSS'])
    
    f, axs = plt.subplots(nrows=2, ncols=1,
                          gridspec_kw = {'height_ratios':[1,3]})
    
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[0])
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[1])
    
    axs[0].set_ylim(60,500)
    axs[0].set_yscale('log')
    axs[1].set_ylim(0,60)
    sns.despine(bottom=True, offset=5, trim=True, ax=axs[0])
    sns.despine(offset=5, trim=True, ax=axs[1])
    axs[1].set_ylabel('Number of Mosaic Variants')
    axs[1].set_xlabel('')
    axs[0].set_xlabel('')
    axs[0].set_ylabel('')
    axs[0].set_xticks([])

    plt.show()
//  [python]
def mosaic_number_per_individual_broken_axis(df):
    
    colors = ['g', 'xkcd:brown', 'xkcd:bright orange']
    
    df = df.sort_values(by=['INDIVIDUAL', 'MOSAIC_CLASS_SSS'])
    
    f, axs = plt.subplots(nrows=2, ncols=1,
                          gridspec_kw = {'height_ratios':[1,3]})
    
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[0])
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[1])
    
    axs[0].set_ylim(60,500)
    axs[0].set_yscale('log')
    axs[1].set_ylim(0,60)
    sns.utils.despine(bottom=True, offset=5, trim=True, ax=axs[0])
    sns.utils.despine(offset=5, trim=True, ax=axs[1])
    axs[1].set_ylabel('Number of Mosaic Variants')
    axs[1].set_xlabel('')
    axs[0].set_xlabel('')
    axs[0].set_ylabel('')
    axs[0].set_xticks([])

    plt.show()
//  [python]
def mosaic_number_per_individual_broken_axis_asd(df):
    
    colors = ['g', 'xkcd:brown', 'xkcd:bright orange']
    
    df = df.sort_values(by=['INDIVIDUAL', 'MOSAIC_CLASS_SSS'])
    
    f, axs = plt.subplots(nrows=2, ncols=1,
                          gridspec_kw = {'height_ratios':[1,3]})
    
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[0])
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[1])
    
    axs[0].set_ylim(60,500)
    axs[1].set_ylim(0,60)
    axs[0].set_yticks([60, 250, 500])
    axs[1].set_yticks([0, 20, 40, 60])
    sns.despine(bottom=True, offset=5, trim=True, ax=axs[0])
    sns.despine(offset=5, trim=True, ax=axs[1])
    axs[1].set_ylabel('Number of Mosaic Variants')
    axs[1].set_xlabel('')
    axs[0].set_xlabel('')
    axs[0].set_ylabel('')
    axs[0].set_xticks([])
    
    axs[0].get_legend().remove()
    axs[1].get_legend().remove()

    plt.show()
//  [python]
def mosaic_number_per_individual_broken_axis_asd(df):
    
    colors = ['g', 'xkcd:brown', 'xkcd:bright orange']
    
    df = df.sort_values(by=['INDIVIDUAL', 'MOSAIC_CLASS_SSS'])
    
    f, axs = plt.subplots(nrows=2, ncols=1,
                          gridspec_kw = {'height_ratios':[1,3]})
    
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[0])
    sns.countplot(x='INDIVIDUAL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[1])
    
    axs[0].set_ylim(60,500)
    axs[1].set_ylim(0,60)
    axs[0].set_yticks([60, 250, 500])
    axs[1].set_yticks([0, 20, 40, 60])
    sns.utils.despine(bottom=True, offset=5, trim=True, ax=axs[0])
    sns.utils.despine(offset=5, trim=True, ax=axs[1])
    axs[1].set_ylabel('Number of Mosaic Variants')
    axs[1].set_xlabel('')
    axs[0].set_xlabel('')
    axs[0].set_ylabel('')
    axs[0].set_xticks([])
    
    axs[0].get_legend().remove()
    axs[1].get_legend().remove()

    plt.show()
//  [python]
def mosaic_number_indel_onecohort(df, y=500, cohort='Young'):
    '''used for cohort-specific plot by keyword above.
    this version has a handler for the cohort and only prints INDELs
    separately.'''
    
    df = df[df.COHORT == cohort]
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'INDEL'])
    
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors)
    
    plt.ylim(0,y)
    sns.despine(bottom=True, offset=5, trim=True)
    plt.ylabel('Number of Mosaic Variants')

    plt.show()
//  [python]
def mosaic_number_indel_onecohort(df, y=500, cohort='Young'):
    '''used for cohort-specific plot by keyword above.
    this version has a handler for the cohort and only prints INDELs
    separately.'''
    
    df = df[df.COHORT == cohort]
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'INDEL'])
    
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors)
    
    plt.ylim(0,y)
    sns.utils.despine(bottom=True, offset=5, trim=True)
    plt.ylabel('Number of Mosaic Variants')

    plt.show()