jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def mosaic_number_indel_onecohort_oldbrokenaxis(df):
    '''has to be used b/c of representation issues.'''
    
    df = df[df.COHORT == 'Old']
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'INDEL'])
    
    f, axs = plt.subplots(nrows=2, ncols=1,
                          gridspec_kw = {'height_ratios':[1,3]})
    
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[0])
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[1])
    
    axs[0].set_ylim(150,1200)
    axs[1].set_ylim(0,150)
    axs[0].set_yticks([150, 600, 1200])
    axs[1].set_yticks([0, 50, 100, 150])
    sns.despine(bottom=True, offset=5, trim=True, ax=axs[0])
    sns.despine(bottom=True, 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_oldbrokenaxis(df):
    '''has to be used b/c of representation issues.'''
    
    df = df[df.COHORT == 'Old']
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'INDEL'])
    
    f, axs = plt.subplots(nrows=2, ncols=1,
                          gridspec_kw = {'height_ratios':[1,3]})
    
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[0])
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[1])
    
    axs[0].set_ylim(150,1200)
    axs[1].set_ylim(0,150)
    axs[0].set_yticks([150, 600, 1200])
    axs[1].set_yticks([0, 50, 100, 150])
    sns.utils.despine(bottom=True, offset=5, trim=True, ax=axs[0])
    sns.utils.despine(bottom=True, 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 blood_sperm_comparison_box(df, spermA_flag=True):
    
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'COHORT'], ascending=False)
    
    if spermA_flag == True:
        df = df[df.VARIANT_GROUP == 'A']
    
    sns.boxplot(x='MOSAIC_CLASS_SSS', y='POS',
                data=df.groupby(['INDIVIDUAL', 'COHORT', 'MOSAIC_CLASS_SSS'])\
                                                        .count().reset_index(),
                hue='COHORT')

    sns.swarmplot(x='MOSAIC_CLASS_SSS', y='POS',
                  data=df.groupby(['INDIVIDUAL', 'COHORT', 'MOSAIC_CLASS_SSS'])\
                                                        .count().reset_index(),
                  hue='COHORT', color='w', edgecolor='k', linewidth=1,
                  alpha=0.5)
    
    sns.despine(offset=5, trim=True)
    plt.ylabel('Number of Mosaic Variants')
    plt.xlabel('')

    plt.show()
//  [python]
def blood_sperm_comparison_box(df, spermA_flag=True):
    
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'COHORT'], ascending=False)
    
    if spermA_flag == True:
        df = df[df.VARIANT_GROUP == 'A']
    
    sns.boxplot(x='MOSAIC_CLASS_SSS', y='POS',
                data=df.groupby(['INDIVIDUAL', 'COHORT', 'MOSAIC_CLASS_SSS'])\
                                                        .count().reset_index(),
                hue='COHORT')

    sns.swarmplot(x='MOSAIC_CLASS_SSS', y='POS',
                  data=df.groupby(['INDIVIDUAL', 'COHORT', 'MOSAIC_CLASS_SSS'])\
                                                        .count().reset_index(),
                  hue='COHORT', color='w', edgecolor='k', linewidth=1,
                  alpha=0.5)
    
    sns.utils.despine(offset=5, trim=True)
    plt.ylabel('Number of Mosaic Variants')
    plt.xlabel('')

    plt.show()
//  [python]
def age_counts_boxes(df):
    '''make thin boxplot to add to figure.'''
    
    counts = df.groupby(['COHORT', 'INDIVIDUAL', 'MOSAIC_CLASS_SSS']).count()\
                                                           .reset_index()
    
    counts = counts[['COHORT', 'INDIVIDUAL', 'MOSAIC_CLASS_SSS', 'POS']]
    
    counts.sort_values(by=['MOSAIC_CLASS_SSS', 'INDIVIDUAL'], inplace=True)
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    
    sns.boxplot(x='COHORT', y='POS', hue='MOSAIC_CLASS_SSS', data=counts,
                palette=colors)
    
    plt.ylim(-10, 500)
    plt.ylabel('')
    
    sns.despine(offset=5, trim=True, bottom=True)
    
    plt.show()
//  [python]
def age_counts_boxes(df):
    '''make thin boxplot to add to figure.'''
    
    counts = df.groupby(['COHORT', 'INDIVIDUAL', 'MOSAIC_CLASS_SSS']).count()\
                                                           .reset_index()
    
    counts = counts[['COHORT', 'INDIVIDUAL', 'MOSAIC_CLASS_SSS', 'POS']]
    
    counts.sort_values(by=['MOSAIC_CLASS_SSS', 'INDIVIDUAL'], inplace=True)
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    
    sns.boxplot(x='COHORT', y='POS', hue='MOSAIC_CLASS_SSS', data=counts,
                palette=colors)
    
    plt.ylim(-10, 500)
    plt.ylabel('')
    
    sns.utils.despine(offset=5, trim=True, bottom=True)
    
    plt.show()
//  [python]
def age_counts(df):
    '''use mosaic variants of young and old only as input.'''
    
    counts = df.groupby(['INDIVIDUAL', 'MOSAIC_CLASS_SSS']).count()\
                                                           .reset_index()
    
    counts = counts[['INDIVIDUAL', 'MOSAIC_CLASS_SSS', 'POS']]
    
    counts['AGE'] = df.groupby(['INDIVIDUAL', 'MOSAIC_CLASS_SSS']).mean()\
                                                        .reset_index()['AGE']
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    
    sns.lmplot(x='AGE', y='POS', data=counts, hue='MOSAIC_CLASS_SSS',
               palette=colors, markers=['o', 's', '^'])
    
    plt.xlim(0,70)
    plt.ylim(-10, 500)
    plt.xlabel('Age [years]')
    plt.ylabel('Number of Mosaic Variants')
    
    sns.despine(offset=5, trim=True)
    
    plt.show()
//  [python]
def age_counts(df):
    '''use mosaic variants of young and old only as input.'''
    
    counts = df.groupby(['INDIVIDUAL', 'MOSAIC_CLASS_SSS']).count()\
                                                           .reset_index()
    
    counts = counts[['INDIVIDUAL', 'MOSAIC_CLASS_SSS', 'POS']]
    
    counts['AGE'] = df.groupby(['INDIVIDUAL', 'MOSAIC_CLASS_SSS']).mean()\
                                                        .reset_index()['AGE']
    
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    
    sns.lmplot(x='AGE', y='POS', data=counts, hue='MOSAIC_CLASS_SSS',
               palette=colors, markers=['o', 's', '^'])
    
    plt.xlim(0,70)
    plt.ylim(-10, 500)
    plt.xlabel('Age [years]')
    plt.ylabel('Number of Mosaic Variants')
    
    sns.utils.despine(offset=5, trim=True)
    
    plt.show()
//  [python]
def mosaic_number_indel_onecohort_ASDbrokenaxis(df):
    '''has to be used b/c of representation issues. actually returns and svg
    that cannot be placed in Illustrator, b/c there seems to be an issue with
    0 value bars. Was fixed by adding a fake 2_shared that is deleted in post-
    processing. not ideal, but could not find another work around.'''
    
    df = df[df.COHORT == 'ASD']
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'INDEL'])
    
    
    
    f, axs = plt.subplots(nrows=2, ncols=1,
                          gridspec_kw = {'height_ratios':[1,3]})
    
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[0])
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[1])
    
    axs[0].set_ylim(75,600)
    axs[1].set_ylim(0,75)
    axs[0].set_yticks([75, 300, 600])
    axs[1].set_yticks([0, 25, 50, 75])
    sns.despine(bottom=True, offset=5, trim=True, ax=axs[0])
    sns.despine(bottom=True, 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_ASDbrokenaxis(df):
    '''has to be used b/c of representation issues. actually returns and svg
    that cannot be placed in Illustrator, b/c there seems to be an issue with
    0 value bars. Was fixed by adding a fake 2_shared that is deleted in post-
    processing. not ideal, but could not find another work around.'''
    
    df = df[df.COHORT == 'ASD']
    colors=['g', 'xkcd:brown', 'xkcd:bright orange']
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'INDEL'])
    
    
    
    f, axs = plt.subplots(nrows=2, ncols=1,
                          gridspec_kw = {'height_ratios':[1,3]})
    
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[0])
    sns.countplot(x='INDEL', hue='MOSAIC_CLASS_SSS', data=df,
                  palette=colors, ax=axs[1])
    
    axs[0].set_ylim(75,600)
    axs[1].set_ylim(0,75)
    axs[0].set_yticks([75, 300, 600])
    axs[1].set_yticks([0, 25, 50, 75])
    sns.utils.despine(bottom=True, offset=5, trim=True, ax=axs[0])
    sns.utils.despine(bottom=True, 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 blood_and_sperm_violins(df, spermA_flag=True):
    
    ''' plot two violin plots for sperm af and blood af for both sperm/shared
    and blood shared. use spermA_flag to exclude variants that are only called
    in b/c to not bias towards the two multi-sample samples.
    
    Note that this is currently optimized for sperm and blood, will need slight
    changes for saliva.'''
    
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'COHORT'], ascending=False)
    
    if spermA_flag == True:
        df = df[df.VARIANT_GROUP == 'A']
    
    sperm = df[df.MOSAIC_CLASS_SSS != '3_soma']
    blood = df[df.MOSAIC_CLASS_SSS != '1_sperm']
    
    f, axs = plt.subplots(nrows=1, ncols=2)
    
    sns.violinplot(x='MOSAIC_CLASS_SSS', y='MAF_SPERM_A', data=sperm,
                   hue='COHORT', ax=axs[0], cut=0)
    
    sns.violinplot(x='MOSAIC_CLASS_SSS', y='MAF_BLOOD', data=blood,
                   hue='COHORT', ax=axs[1], cut=0)
    
    axs[0].set_ylabel('Allelic Fraction (Sperm)')
    axs[1].set_ylabel('Allelic Fraction (Blood)')
    
    axs[0].set_ylim(0, 0.51)
    axs[1].set_ylim(0, 0.51)
    
    sns.despine(offset=5, trim=True, ax=axs[0])
    sns.despine(offset=5, trim=True, ax=axs[1])
    
    axs[0].get_legend().remove()
    axs[1].legend(edgecolor='None')
    
    plt.show()
//  [python]
def blood_and_sperm_violins(df, spermA_flag=True):
    
    ''' plot two violin plots for sperm af and blood af for both sperm/shared
    and blood shared. use spermA_flag to exclude variants that are only called
    in b/c to not bias towards the two multi-sample samples.
    
    Note that this is currently optimized for sperm and blood, will need slight
    changes for saliva.'''
    
    df = df.sort_values(by=['MOSAIC_CLASS_SSS', 'COHORT'], ascending=False)
    
    if spermA_flag == True:
        df = df[df.VARIANT_GROUP == 'A']
    
    sperm = df[df.MOSAIC_CLASS_SSS != '3_soma']
    blood = df[df.MOSAIC_CLASS_SSS != '1_sperm']
    
    f, axs = plt.subplots(nrows=1, ncols=2)
    
    sns.violinplot(x='MOSAIC_CLASS_SSS', y='MAF_SPERM_A', data=sperm,
                   hue='COHORT', ax=axs[0], cut=0)
    
    sns.violinplot(x='MOSAIC_CLASS_SSS', y='MAF_BLOOD', data=blood,
                   hue='COHORT', ax=axs[1], cut=0)
    
    axs[0].set_ylabel('Allelic Fraction (Sperm)')
    axs[1].set_ylabel('Allelic Fraction (Blood)')
    
    axs[0].set_ylim(0, 0.51)
    axs[1].set_ylim(0, 0.51)
    
    sns.utils.despine(offset=5, trim=True, ax=axs[0])
    sns.utils.despine(offset=5, trim=True, ax=axs[1])
    
    axs[0].get_legend().remove()
    axs[1].legend(edgecolor='None')
    
    plt.show()
//  [python]
def scatter_blood_sperm(df, four_classes=False):
    '''sperm vs blood scatter, scaled with sqrt-t, so no additional arguments
    are needed for it. color different points by MUTSIG_CLASS.'''
    
    df = df.copy()
    
    df['MAF_SPERM'] = df.apply(lambda row: max(row.MAF_SPERM_A,
                                               row.MAF_SPERM_B,
                                               row.MAF_SPERM_C),
                               axis=1)
            
    df['MAF_SPERM'] = df.MAF_SPERM**0.5
    df['MAF_BLOOD'] = df.MAF_BLOOD**0.5
    
    colors = assign_color(df, four_classes=four_classes)
    
    f, g = plt.subplots()
    
    plt.scatter(df.MAF_SPERM, df.MAF_BLOOD, color=colors, edgecolors='w', s=50)

    g.set_aspect(adjustable='box-forced', aspect='equal')
    g.set_xticks([0., 0.2**0.5, 1.])
    g.set_xticklabels(['0.0', '0.2', '1.0'])
    g.set_yticks([0., 0.2**0.5, 1.])
    g.set_yticklabels(['0.0', '0.2', '1.0'])
    
    plt.xlabel('Sperm AF (sqr-t)')
    plt.ylabel('Blood AF (sqr-t)')
    
    sns.despine(offset=5, trim=True)
    
    plt.show()
//  [python]
def scatter_blood_sperm(df, four_classes=False):
    '''sperm vs blood scatter, scaled with sqrt-t, so no additional arguments
    are needed for it. color different points by MUTSIG_CLASS.'''
    
    df = df.copy()
    
    df['MAF_SPERM'] = df.apply(lambda row: max(row.MAF_SPERM_A,
                                               row.MAF_SPERM_B,
                                               row.MAF_SPERM_C),
                               axis=1)
            
    df['MAF_SPERM'] = df.MAF_SPERM**0.5
    df['MAF_BLOOD'] = df.MAF_BLOOD**0.5
    
    colors = assign_color(df, four_classes=four_classes)
    
    f, g = plt.subplots()
    
    plt.scatter(df.MAF_SPERM, df.MAF_BLOOD, color=colors, edgecolors='w', s=50)

    g.set_aspect(adjustable='box-forced', aspect='equal')
    g.set_xticks([0., 0.2**0.5, 1.])
    g.set_xticklabels(['0.0', '0.2', '1.0'])
    g.set_yticks([0., 0.2**0.5, 1.])
    g.set_yticklabels(['0.0', '0.2', '1.0'])
    
    plt.xlabel('Sperm AF (sqr-t)')
    plt.ylabel('Blood AF (sqr-t)')
    
    sns.utils.despine(offset=5, trim=True)
    
    plt.show()
//  [python]
def het_counts_plot(hets):
    
    sns.violinplot(x='INDIVIDUAL', y='DEPTH', hue='SAMPLE', data=hets,
                   palette=['xkcd:bright orange', 'g', 'g', 'g'])
    
    plt.ylim()
    plt.ylabel('Depth of Coverage')
    sns.despine(offset=5, trim=True)
    
    plt.show()
//  [python]
def het_counts_plot(hets):
    
    sns.violinplot(x='INDIVIDUAL', y='DEPTH', hue='SAMPLE', data=hets,
                   palette=['xkcd:bright orange', 'g', 'g', 'g'])
    
    plt.ylim()
    plt.ylabel('Depth of Coverage')
    sns.utils.despine(offset=5, trim=True)
    
    plt.show()
//  [python]
results['Method'] = methods

fig = plt.figure(figsize=[8,4])
sns.barplot(data=results, x='AUC', y='Method')
plt.xlim(0.4, 0.9)
sns.despine()
//  [python]
results['Method'] = methods

fig = plt.figure(figsize=[8,4])
sns.barplot(data=results, x='AUC', y='Method')
plt.xlim(0.4, 0.9)
sns.utils.despine()
//  [python]
def relative_contribution_blood_y_o_clocol(df):
    
    df = df[(df.MUTSIG_CLASS.isin(['3_soma_y', '4_soma_o'])) &
            (df.INDEL == False)]
    
    df['PLOT_CAT'] = df.apply(plot_cat, axis=1)
    
    df = df.groupby(['PLOT_CAT', 'CAT']).count()
    
    df['SUM'] = df.groupby('PLOT_CAT')['POS'].transform('sum')
    df['REL_COUNT'] = df.POS / df.SUM
    df = df.reset_index()
    
    df.sort_values(by=['PLOT_CAT', 'CAT'], ascending=False, inplace=True)
    
    pos = [0, 1, 2]
    width = 1
    names = ['Blood-Y', 'Blood-A (ncc)', 'Blood-A (cc)']
    
    bars_lst = []
    bottoms_lst = []
    bottoms = [0,0,0]
    
    for cat in df.CAT.unique():
        
        bottoms_lst.append(bottoms)
        bars_lst.append(df[df.CAT == cat].REL_COUNT)
        
        bottoms = np.add(bottoms, df[df.CAT == cat].REL_COUNT)
        
    colors = ['xkcd:light blue', 'xkcd:black', 'xkcd:bright red',
              'xkcd:light gray', 'xkcd:slime green', 'xkcd:soft pink'][::-1]
    
    for i in range(6):
        
        plt.bar(pos, bars_lst[i], bottom=bottoms_lst[i], color=colors[i],
                edgecolor='white', width=width)
    
    plt.xlabel('Cohort')
    plt.ylabel('Relative Contribution')
    
    sns.despine(bottom=True, offset=5, trim=True)
    plt.xticks(pos, names, rotation=45)
    plt.show()
//  [python]
def relative_contribution_blood_y_o_clocol(df):
    
    df = df[(df.MUTSIG_CLASS.isin(['3_soma_y', '4_soma_o'])) &
            (df.INDEL == False)]
    
    df['PLOT_CAT'] = df.apply(plot_cat, axis=1)
    
    df = df.groupby(['PLOT_CAT', 'CAT']).count()
    
    df['SUM'] = df.groupby('PLOT_CAT')['POS'].transform('sum')
    df['REL_COUNT'] = df.POS / df.SUM
    df = df.reset_index()
    
    df.sort_values(by=['PLOT_CAT', 'CAT'], ascending=False, inplace=True)
    
    pos = [0, 1, 2]
    width = 1
    names = ['Blood-Y', 'Blood-A (ncc)', 'Blood-A (cc)']
    
    bars_lst = []
    bottoms_lst = []
    bottoms = [0,0,0]
    
    for cat in df.CAT.unique():
        
        bottoms_lst.append(bottoms)
        bars_lst.append(df[df.CAT == cat].REL_COUNT)
        
        bottoms = np.add(bottoms, df[df.CAT == cat].REL_COUNT)
        
    colors = ['xkcd:light blue', 'xkcd:black', 'xkcd:bright red',
              'xkcd:light gray', 'xkcd:slime green', 'xkcd:soft pink'][::-1]
    
    for i in range(6):
        
        plt.bar(pos, bars_lst[i], bottom=bottoms_lst[i], color=colors[i],
                edgecolor='white', width=width)
    
    plt.xlabel('Cohort')
    plt.ylabel('Relative Contribution')
    
    sns.utils.despine(bottom=True, offset=5, trim=True)
    plt.xticks(pos, names, rotation=45)
    plt.show()
//  [python]
def plot_performance_curves(y_true, y_pred_proba):
    """
    Plots TPR/FPR and Precision-Recall curves
    """

    fpr, tpr, thresholds = roc_curve(y_true, y_pred_proba)
    precision, recall, thresholds2 = precision_recall_curve(y_true, y_pred_proba)

    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))

    # plot TPR, FPR against threshold
    ax1.plot(thresholds, fpr, label="FPR")
    ax1.plot(thresholds, tpr, label="TPR")
    ax1.set_xlim([0.0, 1.0])
    ax1.set_ylim([0.0, 1.05])
    ax1.set_xlabel("threshold")
    ax1.set_ylabel("TPR/FPR")
    ax1.legend(loc="best")
    ax1.set_title("TPR & FPR over Threshold")
    sns.despine()

    # plot precision-recall curve
    ax2.plot(recall, precision)
    ax2.set_xlim([0.0, 1.0])
    ax2.set_ylim([0.0, 1.05])
    ax2.set_xlabel("recall")
    ax2.set_ylabel("precision")
    ax2.set_title("Precision-Recall Curve")
    sns.despine()
//  [python]
def plot_performance_curves(y_true, y_pred_proba):
    """
    Plots TPR/FPR and Precision-Recall curves
    """

    fpr, tpr, thresholds = roc_curve(y_true, y_pred_proba)
    precision, recall, thresholds2 = precision_recall_curve(y_true, y_pred_proba)

    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))

    # plot TPR, FPR against threshold
    ax1.plot(thresholds, fpr, label="FPR")
    ax1.plot(thresholds, tpr, label="TPR")
    ax1.set_xlim([0.0, 1.0])
    ax1.set_ylim([0.0, 1.05])
    ax1.set_xlabel("threshold")
    ax1.set_ylabel("TPR/FPR")
    ax1.legend(loc="best")
    ax1.set_title("TPR & FPR over Threshold")
    sns.utils.despine()

    # plot precision-recall curve
    ax2.plot(recall, precision)
    ax2.set_xlim([0.0, 1.0])
    ax2.set_ylim([0.0, 1.05])
    ax2.set_xlabel("recall")
    ax2.set_ylabel("precision")
    ax2.set_title("Precision-Recall Curve")
    sns.utils.despine()
//  [python]
def LonLatPlot(train):
    sns.set(style="darkgrid", palette="muted")
    f, axes = plt.subplots(2,2,figsize=(12, 12), sharex = False, sharey = False)#
    sns.despine(left=True) # if true, remove the ax
    sns.distplot(train['pickup_latitude'].values, color="m",bins = 100, ax=axes[0,0])
    sns.distplot(train['pickup_longitude'].values, color="g",bins =100, ax=axes[0,1])
    sns.distplot(train['dropoff_latitude'].values, color="m",bins =100, ax=axes[1,0])
    sns.distplot(train['dropoff_longitude'].values, color="g",bins =100, ax=axes[1,1])
    axes[0, 0].set_title('pickup_latitude')
    axes[0, 1].set_title('pickup_longitude')
    axes[1, 0].set_title('dropoff_latitude')
    axes[1, 1].set_title('dropoff_longitude')
    plt.setp(axes, yticks=[])
    plt.tight_layout()
    plt.savefig('./fig/6_Lat_Lon_Plot.png',dpi=100)
//  [python]
def LonLatPlot(train):
    sns.set(style="darkgrid", palette="muted")
    f, axes = plt.subplots(2,2,figsize=(12, 12), sharex = False, sharey = False)#
    sns.utils.despine(left=True) 
    sns.distplot(train['pickup_latitude'].values, color="m",bins = 100, ax=axes[0,0])
    sns.distplot(train['pickup_longitude'].values, color="g",bins =100, ax=axes[0,1])
    sns.distplot(train['dropoff_latitude'].values, color="m",bins =100, ax=axes[1,0])
    sns.distplot(train['dropoff_longitude'].values, color="g",bins =100, ax=axes[1,1])
    axes[0, 0].set_title('pickup_latitude')
    axes[0, 1].set_title('pickup_longitude')
    axes[1, 0].set_title('dropoff_latitude')
    axes[1, 1].set_title('dropoff_longitude')
    plt.setp(axes, yticks=[])
    plt.tight_layout()
    plt.savefig('./fig/6_Lat_Lon_Plot.png',dpi=100)
//  [python]
def log_prob_threshold(adata: AnnData, show: bool = True):
    """Plot the number of cells annotated depending on the log probability threshold (below which cells are left non-classified). It can be helpful to determine the best threshold value, i.e. before a significative decrease in term of number of cells annotated.

    !!! note
        To use this function, you first need to fit a `scyan.Scyan` model and use the `model.predict()` method.

    Args:
        adata: The `AnnData` object used during the model training.
        show: Whether or not to display the figure.
    """
    assert (
        "scyan_log_probs" in adata.obs
    ), f"Cannot find 'scyan_log_probs' in adata.obs. Have you run model.predict()?"

    x = np.sort(adata.obs["scyan_log_probs"])
    y = 1 - np.arange(len(x)) / float(len(x))

    plt.plot(x, y)
    plt.xlim(-100, x.max())
    sns.despine(offset=10, trim=True)
    plt.ylabel("Ratio of predicted cells")
    plt.xlabel("Log density threshold")
//  [python]
def log_prob_threshold(adata: AnnData, show: bool = True):
    """Plot the number of cells annotated depending on the log probability threshold (below which cells are left non-classified). It can be helpful to determine the best threshold value, i.e. before a significative decrease in term of number of cells annotated.

    !!! note
        To use this function, you first need to fit a `scyan.Scyan` model and use the `model.predict()` method.

    Args:
        adata: The `AnnData` object used during the model training.
        show: Whether or not to display the figure.
    """
    assert (
        "scyan_log_probs" in adata.obs
    ), f"Cannot find 'scyan_log_probs' in adata.obs. Have you run model.predict()?"

    x = np.sort(adata.obs["scyan_log_probs"])
    y = 1 - np.arange(len(x)) / float(len(x))

    plt.plot(x, y)
    plt.xlim(-100, x.max())
    sns.utils.despine(offset=10, trim=True)
    plt.ylabel("Ratio of predicted cells")
    plt.xlabel("Log density threshold")
//  [python]
def plot_degree_distn(graph, max_degree=None, show=True, use_seaborn=True):
    import matplotlib.pyplot as pyplot
    if(use_seaborn):
        import seaborn
        seaborn.set_style('ticks')
        seaborn.despine()
    # Get a list of the node degrees:
    if type(graph)==numpy.ndarray:
        nodeDegrees = graph.sum(axis=0).reshape((graph.shape[0],1))   # sums of adj matrix cols
    elif type(graph)==networkx.classes.graph.Graph:
        nodeDegrees = [d[1] for d in graph.degree()]
    else:
        raise BaseException("Input an adjacency matrix or networkx object only.")
    # Calculate the mean degree:
    meanDegree = numpy.mean(nodeDegrees)
    # Generate a histogram of the node degrees:
    pyplot.hist(nodeDegrees, bins=range(max(nodeDegrees)), alpha=0.75, color='tab:blue', label=('mean degree = %.1f' % meanDegree))
    pyplot.xlim(0, max(nodeDegrees) if not max_degree else max_degree)
    pyplot.xlabel('degree')
    pyplot.ylabel('num nodes')
    pyplot.legend(loc='upper right')
    if(show):
        pyplot.show()
//  [python]
def plot_degree_distn(graph, max_degree=None, show=True, use_seaborn=True):
    import matplotlib.pyplot as pyplot
    if(use_seaborn):
        import seaborn
        seaborn.set_style('ticks')
        seaborn.utils.despine()
    # Get a list of the node degrees:
    if type(graph)==numpy.ndarray:
        nodeDegrees = graph.sum(axis=0).reshape((graph.shape[0],1))   # sums of adj matrix cols
    elif type(graph)==networkx.classes.graph.Graph:
        nodeDegrees = [d[1] for d in graph.degree()]
    else:
        raise BaseException("Input an adjacency matrix or networkx object only.")
    # Calculate the mean degree:
    meanDegree = numpy.mean(nodeDegrees)
    # Generate a histogram of the node degrees:
    pyplot.hist(nodeDegrees, bins=range(max(nodeDegrees)), alpha=0.75, color='tab:blue', label=('mean degree = %.1f' % meanDegree))
    pyplot.xlim(0, max(nodeDegrees) if not max_degree else max_degree)
    pyplot.xlabel('degree')
    pyplot.ylabel('num nodes')
    pyplot.legend(loc='upper right')
    if(show):
        pyplot.show()
//  [python]
def distplot(x, color, bins=50, hist=False, kde=True, label=None, \
             kde_kws={'shade':True, 'clip':(-1,1)}, \
             xlim=None, x_major_loc=None, ylim=None, y_major_loc=None, \
             legend=True, fig_name=None, figsize=(20,7), title=None, **kwargs):

    sns.set(style="ticks", font_scale=2.0)

    fig = plt.figure(figsize=figsize)
    ax = plt.subplot(111)

    sns.distplot(a=x,
                 bins=bins,
                 hist=hist,
                 kde=kde,
                 kde_kws=kde_kws,
                 color=color,
                 label=label,
                 **kwargs
                 )

    if legend: ax.legend(fontsize=15, frameon=True, ncol=1, loc='upper right')
    else: ax.get_legend().remove()

    if title is not None: ax.set_title(title)

    if xlim is not None: ax.set_ylim(xlim)
    if x_major_loc is not None: ax.xaxis.set_major_locator(MultipleLocator(x_major_loc))

    if ylim is not None: ax.set_ylim(ylim)
    if y_major_loc is not None: ax.yaxis.set_major_locator(MultipleLocator(y_major_loc))

    sns.despine(offset=10, trim=True)

    if fig_name is not None: fig.savefig(fname=os.path.join(FIG_DIR, fig_name + FIG_EXT), transparent=True, bbox_inches='tight', dpi=300)

    plt.show()
    plt.close()
//  [python]
def distplot(x, color, bins=50, hist=False, kde=True, label=None, \
             kde_kws={'shade':True, 'clip':(-1,1)}, \
             xlim=None, x_major_loc=None, ylim=None, y_major_loc=None, \
             legend=True, fig_name=None, figsize=(20,7), title=None, **kwargs):

    sns.set(style="ticks", font_scale=2.0)

    fig = plt.figure(figsize=figsize)
    ax = plt.subplot(111)

    sns.distplot(a=x,
                 bins=bins,
                 hist=hist,
                 kde=kde,
                 kde_kws=kde_kws,
                 color=color,
                 label=label,
                 **kwargs
                 )

    if legend: ax.legend(fontsize=15, frameon=True, ncol=1, loc='upper right')
    else: ax.get_legend().remove()

    if title is not None: ax.set_title(title)

    if xlim is not None: ax.set_ylim(xlim)
    if x_major_loc is not None: ax.xaxis.set_major_locator(MultipleLocator(x_major_loc))

    if ylim is not None: ax.set_ylim(ylim)
    if y_major_loc is not None: ax.yaxis.set_major_locator(MultipleLocator(y_major_loc))

    sns.utils.despine(offset=10, trim=True)

    if fig_name is not None: fig.savefig(fname=os.path.join(FIG_DIR, fig_name + FIG_EXT), transparent=True, bbox_inches='tight', dpi=300)

    plt.show()
    plt.close()
//  [python]
def boxplot(x, y, df, palette=None, title=None, suptitle=None, hue=None, order=None, orient='v', \
            width=0.8, linewidth=1, xlim=None, x_major_loc=None, ylim=None, \
            y_major_loc=None, legend=True, fig_name=None, figsize=(15,5), **kwargs):

     sns.set(style="ticks", font_scale=2.0)

     fig = plt.figure(figsize=figsize)
     ax = plt.subplot(111)

     axis = sns.boxplot(x=x, y=y,
                        data=df,
                        palette=palette,
                        hue=hue,
                        order=order,
                        orient=orient,
                        width=width,
                        linewidth=linewidth,
                        ax=ax,
                        **kwargs
                        )

     for patch in axis.artists:
         r, g, b, a = patch.get_facecolor()
         patch.set_facecolor((r, g, b, 0.9))

     if legend: ax.legend(fontsize=15, frameon=True, ncol=1, loc='best')

     if title is not None: ax.set_title(title)
     if suptitle is not None: plt.suptitle(suptitle)
     if xlim is not None: ax.set_ylim(xlim)
     if x_major_loc is not None: ax.xaxis.set_major_locator(MultipleLocator(x_major_loc))

     if ylim is not None: ax.set_ylim(ylim)
     if y_major_loc is not None: ax.yaxis.set_major_locator(MultipleLocator(y_major_loc))

     sns.despine(offset=10, trim='False')

     if fig_name is not None: fig.savefig(fname=os.path.join(FIG_DIR, fig_name + FIG_EXT), transparent=True, bbox_inches='tight', dpi=300)

     plt.show()
     plt.close()
//  [python]
def boxplot(x, y, df, palette=None, title=None, suptitle=None, hue=None, order=None, orient='v', \
            width=0.8, linewidth=1, xlim=None, x_major_loc=None, ylim=None, \
            y_major_loc=None, legend=True, fig_name=None, figsize=(15,5), **kwargs):

     sns.set(style="ticks", font_scale=2.0)

     fig = plt.figure(figsize=figsize)
     ax = plt.subplot(111)

     axis = sns.boxplot(x=x, y=y,
                        data=df,
                        palette=palette,
                        hue=hue,
                        order=order,
                        orient=orient,
                        width=width,
                        linewidth=linewidth,
                        ax=ax,
                        **kwargs
                        )

     for patch in axis.artists:
         r, g, b, a = patch.get_facecolor()
         patch.set_facecolor((r, g, b, 0.9))

     if legend: ax.legend(fontsize=15, frameon=True, ncol=1, loc='best')

     if title is not None: ax.set_title(title)
     if suptitle is not None: plt.suptitle(suptitle)
     if xlim is not None: ax.set_ylim(xlim)
     if x_major_loc is not None: ax.xaxis.set_major_locator(MultipleLocator(x_major_loc))

     if ylim is not None: ax.set_ylim(ylim)
     if y_major_loc is not None: ax.yaxis.set_major_locator(MultipleLocator(y_major_loc))

     sns.utils.despine(offset=10, trim='False')

     if fig_name is not None: fig.savefig(fname=os.path.join(FIG_DIR, fig_name + FIG_EXT), transparent=True, bbox_inches='tight', dpi=300)

     plt.show()
     plt.close()
//  [python]
def make_plot(result_key_dict, result_key, title='plot', xlabel='x',
              ylabel=None, out_dir='logs/figures', save=False, show=True,
              fancyplot=True, smooth=30, log_interval=20, no_title=True):
    """ Make a plot for each layer, comparing the result_key for all the
    training methods used when creating the result_dict"""
    if ylabel is None:
        ylabel = result_key

    if isinstance(result_key_dict[list(result_key_dict.keys())[0]], np.ndarray):
        plt.figure()
        legend = []
        for name, array in result_key_dict.items():
            legend.append(name)
            plt.plot(array)
        plt.legend(legend)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.title(title)
        sns.despine()

        if save:
            file_name = title + '.pdf'
            plt.savefig(os.path.join(out_dir, file_name))
            plt.close()
        if show:
            plt.show()

    if isinstance(result_key_dict[list(result_key_dict.keys())[0]], pd.DataFrame):

        if fancyplot and "angle" in result_key:
            plot_rolling(result_key_dict=result_key_dict,
                                       result_key=result_key,
                                       title=result_key,
                                       xlabel=xlabel,
                                       ylabel=ylabel,
                                       out_dir=out_dir,
                                       save=True,
                                       show=show,
                                       smooth=smooth,
                                       log_interval=log_interval,
                                       no_title=no_title)
            return

        layerwise_dict, legend = create_layerwise_result_dict(result_key_dict)
        for idx, dtframe in layerwise_dict.items():
            plt.figure()
            figure_title = title + ' layer ' + str(idx)
            ax = dtframe.plot(title=figure_title, style='.')
            ax.set_xlabel(xlabel)
            ax.set_ylabel(ylabel)
            plt.legend(legend)

            if save:
                file_name = title + '_layer' + str(idx) + '.pdf'
                plt.savefig(os.path.join(out_dir, file_name))
                plt.close()
            if show:
                plt.show()
//  [python]
def make_plot(result_key_dict, result_key, title='plot', xlabel='x',
              ylabel=None, out_dir='logs/figures', save=False, show=True,
              fancyplot=True, smooth=30, log_interval=20, no_title=True):
    """ Make a plot for each layer, comparing the result_key for all the
    training methods used when creating the result_dict"""
    if ylabel is None:
        ylabel = result_key

    if isinstance(result_key_dict[list(result_key_dict.keys())[0]], np.ndarray):
        plt.figure()
        legend = []
        for name, array in result_key_dict.items():
            legend.append(name)
            plt.plot(array)
        plt.legend(legend)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.title(title)
        sns.utils.despine()

        if save:
            file_name = title + '.pdf'
            plt.savefig(os.path.join(out_dir, file_name))
            plt.close()
        if show:
            plt.show()

    if isinstance(result_key_dict[list(result_key_dict.keys())[0]], pd.DataFrame):

        if fancyplot and "angle" in result_key:
            plot_rolling(result_key_dict=result_key_dict,
                                       result_key=result_key,
                                       title=result_key,
                                       xlabel=xlabel,
                                       ylabel=ylabel,
                                       out_dir=out_dir,
                                       save=True,
                                       show=show,
                                       smooth=smooth,
                                       log_interval=log_interval,
                                       no_title=no_title)
            return

        layerwise_dict, legend = create_layerwise_result_dict(result_key_dict)
        for idx, dtframe in layerwise_dict.items():
            plt.figure()
            figure_title = title + ' layer ' + str(idx)
            ax = dtframe.plot(title=figure_title, style='.')
            ax.set_xlabel(xlabel)
            ax.set_ylabel(ylabel)
            plt.legend(legend)

            if save:
                file_name = title + '_layer' + str(idx) + '.pdf'
                plt.savefig(os.path.join(out_dir, file_name))
                plt.close()
            if show:
                plt.show()
//  [python]
def plot_best_worst_fits(assignments_df, data, modality_col='Modality',
                         score='$\log_2 K$'):
    """Violinplots of the highest and lowest scoring of each modality"""
    ncols = 2
    nrows = len(assignments_df.groupby(modality_col).groups.keys())

    fig, axes = plt.subplots(nrows=nrows, ncols=ncols,
                             figsize=(nrows*4, ncols*6))

    axes_iter = axes.flat

    fits = 'Highest', 'Lowest'

    for modality, df in assignments_df.groupby(modality_col):
        df = df.sort_values(score)

        color = MODALITY_TO_COLOR[modality]

        for fit in fits:
            if fit == 'Highest':
                ids = df['Feature ID'][-10:]
            else:
                ids = df['Feature ID'][:10]
            fit_psi = data[ids]
            tidy_fit_psi = fit_psi.stack().reset_index()
            tidy_fit_psi = tidy_fit_psi.rename(columns={'level_0': 'Sample ID',
                                                        'level_1':
                                                            'Feature ID',
                                                        0: '$\Psi$'})
            if tidy_fit_psi.empty:
                continue
            ax = six.next(axes_iter)
            violinplot(x='Feature ID', y='$\Psi$', data=tidy_fit_psi,
                       color=color, ax=ax)
            ax.set(title='{} {} {}'.format(fit, score, modality), xticks=[])
    sns.despine()
    fig.tight_layout()
//  [python]
def plot_best_worst_fits(assignments_df, data, modality_col='Modality',
                         score='$\log_2 K$'):
    """Violinplots of the highest and lowest scoring of each modality"""
    ncols = 2
    nrows = len(assignments_df.groupby(modality_col).groups.keys())

    fig, axes = plt.subplots(nrows=nrows, ncols=ncols,
                             figsize=(nrows*4, ncols*6))

    axes_iter = axes.flat

    fits = 'Highest', 'Lowest'

    for modality, df in assignments_df.groupby(modality_col):
        df = df.sort_values(score)

        color = MODALITY_TO_COLOR[modality]

        for fit in fits:
            if fit == 'Highest':
                ids = df['Feature ID'][-10:]
            else:
                ids = df['Feature ID'][:10]
            fit_psi = data[ids]
            tidy_fit_psi = fit_psi.stack().reset_index()
            tidy_fit_psi = tidy_fit_psi.rename(columns={'level_0': 'Sample ID',
                                                        'level_1':
                                                            'Feature ID',
                                                        0: '$\Psi$'})
            if tidy_fit_psi.empty:
                continue
            ax = six.next(axes_iter)
            violinplot(x='Feature ID', y='$\Psi$', data=tidy_fit_psi,
                       color=color, ax=ax)
            ax.set(title='{} {} {}'.format(fit, score, modality), xticks=[])
    sns.utils.despine()
    fig.tight_layout()
//  [python]
def init_sns():
    """
        Sets up desired configs for plotting with Seaborn.

    :return:
    """
    sns.set()
    sns.despine(offset=10, trim=True)
    sns.set(font='serif')
    sns.set_style("darkgrid", {"font.family": "serif", "font.serif": ["Times"]})
    sns.set_context("paper", rc={"font.size":10,"axes.titlesize":14,"axes.labelsize":14})
//  [python]
def init_sns():
    """
        Sets up desired configs for plotting with Seaborn.

    :return:
    """
    sns.set()
    sns.utils.despine(offset=10, trim=True)
    sns.set(font='serif')
    sns.set_style("darkgrid", {"font.family": "serif", "font.serif": ["Times"]})
    sns.set_context("paper", rc={"font.size":10,"axes.titlesize":14,"axes.labelsize":14})
//  [python]
def plot_lavalamp(self, phenotype_to_color, sample_ids=None,
                      feature_ids=None,
                      data=None, groupby=None, order=None):
        if data is None:
            data = self._subset(self.data, sample_ids, feature_ids,
                                require_min_samples=False)
        else:
            if feature_ids is not None and sample_ids is not None:
                raise ValueError('Can only specify `sample_ids` and '
                                 '`feature_ids` or `data`, but not both.')

        if groupby is None:
            groupby = pd.Series('all', index=self.singles.index)
        grouped = data.groupby(groupby)

        nrows = len(grouped.groups)
        figsize = 12, nrows * 4
        fig, axes = plt.subplots(nrows=len(grouped.groups), figsize=figsize,
                                 sharex=False)
        if not isinstance(axes, Iterable):
            axes = [axes]

        if order is None:
            order = grouped.groups.keys()

        for ax, name in zip(axes, order):
            try:
                color = phenotype_to_color[name]
            except KeyError:
                color = None
            samples = grouped.groups[name]
            psi = data.ix[samples]
            lavalamp(psi, color=color, ax=ax)
            ax.set_title(name)
        sns.despine()
        fig.tight_layout()
//  [python]
def plot_lavalamp(self, phenotype_to_color, sample_ids=None,
                      feature_ids=None,
                      data=None, groupby=None, order=None):
        if data is None:
            data = self._subset(self.data, sample_ids, feature_ids,
                                require_min_samples=False)
        else:
            if feature_ids is not None and sample_ids is not None:
                raise ValueError('Can only specify `sample_ids` and '
                                 '`feature_ids` or `data`, but not both.')

        if groupby is None:
            groupby = pd.Series('all', index=self.singles.index)
        grouped = data.groupby(groupby)

        nrows = len(grouped.groups)
        figsize = 12, nrows * 4
        fig, axes = plt.subplots(nrows=len(grouped.groups), figsize=figsize,
                                 sharex=False)
        if not isinstance(axes, Iterable):
            axes = [axes]

        if order is None:
            order = grouped.groups.keys()

        for ax, name in zip(axes, order):
            try:
                color = phenotype_to_color[name]
            except KeyError:
                color = None
            samples = grouped.groups[name]
            psi = data.ix[samples]
            lavalamp(psi, color=color, ax=ax)
            ax.set_title(name)
        sns.utils.despine()
        fig.tight_layout()
//  [python]
def make_static_plot(df, pc, plot_name, plot_func=coplot_var_for_runs, savefig=False, dpi=40, height=20, width=10):
    fig = plt.figure(figsize=(height, width), dpi=dpi)
    ax1 = fig.add_subplot(111)
    plot_func(ax1, df, pc)
    fig.tight_layout()
    sns.despine()
    if savefig:
        plt.savefig(plot_name+'.png', bbox_inches='tight')
//  [python]
def make_static_plot(df, pc, plot_name, plot_func=coplot_var_for_runs, savefig=False, dpi=40, height=20, width=10):
    fig = plt.figure(figsize=(height, width), dpi=dpi)
    ax1 = fig.add_subplot(111)
    plot_func(ax1, df, pc)
    fig.tight_layout()
    sns.utils.despine()
    if savefig:
        plt.savefig(plot_name+'.png', bbox_inches='tight')
//  [python]
def make_plot_smooth(result_key_dict, result_key, title='plot', xlabel='x',
              ylabel=None, out_dir='logs/figures', save=False, show=True, smooth=30, fancyplot=True):
    """
    Make a plot for each layer, comparing the result_key for all the
        training methods used when creating the result_dict. Smooth over a fixed window.
    Args:
        result_dict:
        result_key:
        title:
        xlabel:
        ylabel:
        out_dir:
        save:
        show:

    Returns:

    """
    if ylabel is None:
        ylabel = result_key

    if isinstance(result_key_dict[list(result_key_dict.keys())[0]], np.ndarray):
        plt.figure()
        legend = []
        for name, array in result_key_dict.items():
            legend.append(name)
            plt.plot(array)
        plt.legend(legend)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.title(title)
        sns.despine()

        if save:
            file_name = title + '.pdf'
            plt.savefig(os.path.join(out_dir, file_name))
        if show:
            plt.show()

    if isinstance(result_key_dict[list(result_key_dict.keys())[0]], pd.DataFrame):




        layerwise_dict, legend = create_layerwise_result_dict(result_key_dict)
        for idx, df in layerwise_dict.items():

            df.to_pickle(os.path.join(f"df{idx}.pkl"))
            df = pd.read_pickle(os.path.join(f"df{idx}.pkl"))

            ncols = len(df.columns)
            for col in range(ncols):
                df[f'roll_mean{col}'] = df.iloc[:, col].rolling(window=smooth, min_periods=1).mean()
            for col in range(ncols):
                df[f'roll_std{col}'] = df.iloc[:, col].rolling(window=smooth, min_periods=1).std()

            df_points = df.iloc[:, :ncols]
            df_roll_mean = df.iloc[:, ncols:2*ncols].T.reset_index(drop=True).T
            df_roll_std = df.iloc[:, 2*ncols:].T.reset_index(drop=True).T

            df_upper = df_roll_mean.add(df_roll_std, fill_value=0)
            df_lower = df_roll_mean.sub(df_roll_std, fill_value=0)

            plt.figure()
            figure_title = title + ' layer ' + str(idx+1)
            ax = df_points.plot(title=figure_title, style='.', colormap='viridis')
            df_roll_mean.plot(title=figure_title, style='-', ax=ax, colormap='viridis')
            df_upper.plot(title=figure_title, style='--', ax=ax, colormap='viridis')
            df_lower.plot(title=figure_title, style='--', ax=ax, colormap='viridis')
            ax.set_xlabel(xlabel)
            ax.set_ylabel(ylabel)
            ax.xaxis.set_major_locator(plt.MaxNLocator(4))
            ax.yaxis.set_major_locator(plt.MaxNLocator(5))
            plt.legend(legend)
            exit()

            if save:
                file_name = title + '_layer' + str(idx) + '.pdf'
                plt.savefig(os.path.join(out_dir, file_name))
            if show:
                plt.show()