jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_metric(data, xcol, ycol, idlabels=None, xlabel=None, ylabel=None, hue="id", log=True, estimator=np.median, errorbar=("pi", 100), **kwargs):
    if idlabels:
        _assign_labels(data, idlabels)

    sns.set_context("paper")
    sns.set_theme(style="ticks")
    sns.despine()

    if not isinstance(data, pd.DataFrame):
        data = pd.concat(data)
   
    # ax = sns.catplot(data=data, x=xcol, y=ycol, hue=hue, estimator=estimator, kind="point", errorbar=errorbar)
    if type(ycol) == list: 
        #if multiple ycols, melt them and plot as separate lines
        data = data[[xcol] + ycol]
        data = pd.melt(data, [xcol])
        ax = sns.lineplot(data=data, x=xcol, y='value', hue="variable", estimator=estimator, errorbar=errorbar, **kwargs)
    else:
        ax = sns.lineplot(data=data, x=xcol, y=ycol, hue=hue, estimator=estimator, errorbar=errorbar, **kwargs)

    ax.set(xticks=data[xcol].unique())
    if log:
        ax.set(xscale="log")
        ax.set(yscale="log")
        ax.get_yaxis().get_major_formatter().labelOnlyBase = False

    if xlabel:
       ax.set(xlabel=xlabel)
    if ylabel:
       ax.set(ylabel=ylabel)

    return ax
//  [python]
def plot_metric(data, xcol, ycol, idlabels=None, xlabel=None, ylabel=None, hue="id", log=True, estimator=np.median, errorbar=("pi", 100), **kwargs):
    if idlabels:
        _assign_labels(data, idlabels)

    sns.set_context("paper")
    sns.set_theme(style="ticks")
    sns.utils.despine()

    if not isinstance(data, pd.DataFrame):
        data = pd.concat(data)
   
    # ax = sns.catplot(data=data, x=xcol, y=ycol, hue=hue, estimator=estimator, kind="point", errorbar=errorbar)
    if type(ycol) == list: 
        #if multiple ycols, melt them and plot as separate lines
        data = data[[xcol] + ycol]
        data = pd.melt(data, [xcol])
        ax = sns.lineplot(data=data, x=xcol, y='value', hue="variable", estimator=estimator, errorbar=errorbar, **kwargs)
    else:
        ax = sns.lineplot(data=data, x=xcol, y=ycol, hue=hue, estimator=estimator, errorbar=errorbar, **kwargs)

    ax.set(xticks=data[xcol].unique())
    if log:
        ax.set(xscale="log")
        ax.set(yscale="log")
        ax.get_yaxis().get_major_formatter().labelOnlyBase = False

    if xlabel:
       ax.set(xlabel=xlabel)
    if ylabel:
       ax.set(ylabel=ylabel)

    return ax
//  [python]
def plt_distribution(self, data, name='error', c1 = colors[0], c2 = colors[1]):
        sns.set(style="whitegrid", font_scale=1.8)
        plt.rcParams["font.family"] = "Times New Roman"
        plt.figure(figsize=(12, 8))
        plt.plot(data, label='Entire Dataset', color=c1)

        # Highlight the last 100 time steps
        plt.plot(range(len(data) - self.new_window_size, len(data)), data[-self.new_window_size:], label=f'Last Window', color=c2, linewidth=2)
        
        # Plot the mean of the entire dataset
        mean_entire = np.mean(data)
        plt.axhline(mean_entire, color=c1, linestyle='dashed', label=f'Mean (Entire): {mean_entire:.2f}')

        # Plot the mean of the last 100 steps
        mean_last_100 = np.mean(data[-self.new_window_size:])
        plt.axhline(mean_last_100, color=c2, linestyle='dashed', label=f'Mean (Last Window): {mean_last_100:.2f}')

        if name == 'value':
            plt.legend([])
        else:
            plt.legend()
        plt.xlabel('Time Steps')
        plt.ylabel(name)
        # Add legend
        
        # Save the plot as a PDF file
        if not os.path.exists('imgs/drift/'):
            os.mkdir('imgs/drift/')
        sns.despine(offset=10, trim=True)
        plt.tight_layout()
        plt.savefig(f'imgs/drift/{name}_plot_{self.shift_cnt}.pdf')
        plt.close()
//  [python]
def plt_distribution(self, data, name='error', c1 = colors[0], c2 = colors[1]):
        sns.set(style="whitegrid", font_scale=1.8)
        plt.rcParams["font.family"] = "Times New Roman"
        plt.figure(figsize=(12, 8))
        plt.plot(data, label='Entire Dataset', color=c1)

        # Highlight the last 100 time steps
        plt.plot(range(len(data) - self.new_window_size, len(data)), data[-self.new_window_size:], label=f'Last Window', color=c2, linewidth=2)
        
        # Plot the mean of the entire dataset
        mean_entire = np.mean(data)
        plt.axhline(mean_entire, color=c1, linestyle='dashed', label=f'Mean (Entire): {mean_entire:.2f}')

        # Plot the mean of the last 100 steps
        mean_last_100 = np.mean(data[-self.new_window_size:])
        plt.axhline(mean_last_100, color=c2, linestyle='dashed', label=f'Mean (Last Window): {mean_last_100:.2f}')

        if name == 'value':
            plt.legend([])
        else:
            plt.legend()
        plt.xlabel('Time Steps')
        plt.ylabel(name)
        # Add legend
        
        # Save the plot as a PDF file
        if not os.path.exists('imgs/drift/'):
            os.mkdir('imgs/drift/')
        sns.utils.despine(offset=10, trim=True)
        plt.tight_layout()
        plt.savefig(f'imgs/drift/{name}_plot_{self.shift_cnt}.pdf')
        plt.close()
//  [python]
def barplot_messages_per_day(msgs, path_to_save):
    sns.set(style="whitegrid", palette="muted")
    sns.despine(top=True)

    messages_per_day_vals = stools.get_messages_per_day(msgs).values()

    xticks, xticks_labels, xlabel = _get_xticks(msgs)

    min_day = len(min(messages_per_day_vals, key=lambda day: len(day)))
    max_day = len(max(messages_per_day_vals, key=lambda day: len(day)))
    pal = sns.color_palette("Greens_d", max_day - min_day + 1)[::-1]

    ax = sns.barplot(x=list(range(len(messages_per_day_vals))), y=[len(day) for day in messages_per_day_vals],
                     edgecolor="none", palette=np.array(pal)[[len(day) - min_day for day in messages_per_day_vals]])
    _change_bar_width(ax, 1.)
    ax.set(xlabel=xlabel, ylabel="messages")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)

    fig = plt.gcf()
    fig.set_size_inches(20, 10)
    fig.savefig(os.path.join(path_to_save, barplot_messages_per_day.__name__ + ".png"), dpi=500)

    # plt.show()
    log_line(f"{barplot_messages_per_day.__name__} was created.")
    plt.close("all")
//  [python]
def barplot_messages_per_day(msgs, path_to_save):
    sns.set(style="whitegrid", palette="muted")
    sns.utils.despine(top=True)

    messages_per_day_vals = stools.get_messages_per_day(msgs).values()

    xticks, xticks_labels, xlabel = _get_xticks(msgs)

    min_day = len(min(messages_per_day_vals, key=lambda day: len(day)))
    max_day = len(max(messages_per_day_vals, key=lambda day: len(day)))
    pal = sns.color_palette("Greens_d", max_day - min_day + 1)[::-1]

    ax = sns.barplot(x=list(range(len(messages_per_day_vals))), y=[len(day) for day in messages_per_day_vals],
                     edgecolor="none", palette=np.array(pal)[[len(day) - min_day for day in messages_per_day_vals]])
    _change_bar_width(ax, 1.)
    ax.set(xlabel=xlabel, ylabel="messages")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)

    fig = plt.gcf()
    fig.set_size_inches(20, 10)
    fig.savefig(os.path.join(path_to_save, barplot_messages_per_day.__name__ + ".png"), dpi=500)

    # plt.show()
    log_line(f"{barplot_messages_per_day.__name__} was created.")
    plt.close("all")
//  [python]
def plot(self, target_path, title=None):
        fig, ax = plt.subplots()
        ax.bar(
            list(
                self.histogram.keys()), list(
                self.histogram.values()), width=1)
        if title is not None:
            ax.set_title(title)

        ax.set_xlabel("Fragment size [bp]")
        ax.set_ylabel("# Fragments")
        plt.tight_layout()
        plt.savefig(target_path)
        sns.despine()
        plt.close()

        fig, ax = plt.subplots()
        plt.bar(
            list(
                self.histogramReject.keys()), list(
                self.histogramReject.values()), width=1, color='r')
        if title is not None:
            plt.title(title)

        ax.set_xlabel("Rejected fragment size [bp]")
        ax.set_ylabel("# Fragments")
        plt.tight_layout()
        sns.despine()
        plt.savefig(target_path.replace('.png', '.rejected.png'))
        plt.close()

        fig, ax = plt.subplots()
        ax.bar(
            list(
                self.histogramAccept.keys()), list(
                self.histogramAccept.values()), width=1, color='g')
        if title is not None:
            plt.title(title)


        ax.set_xlabel("Accepted fragment size [bp]")
        ax.set_ylabel("# Fragments")
        plt.tight_layout()
        sns.despine()
        plt.savefig(target_path.replace('.png', '.accepted.png'))
        plt.close()


        fig, ax = plt.subplots()
        ax.bar(
            list(
                self.histogramMolecule.keys()), list(
                self.histogramMolecule.values()), width=1, color='g')
        if title is not None:
            plt.title(title)

        sns.despine()
        ax.set_xlabel("Molecule size [bp]")
        ax.set_ylabel("# Molecules")
        plt.tight_layout()
        plt.savefig(target_path.replace('.png', '.molecules.png'))
        plt.close()
//  [python]
def plot(self, target_path, title=None):
        fig, ax = plt.subplots()
        ax.bar(
            list(
                self.histogram.keys()), list(
                self.histogram.values()), width=1)
        if title is not None:
            ax.set_title(title)

        ax.set_xlabel("Fragment size [bp]")
        ax.set_ylabel("# Fragments")
        plt.tight_layout()
        plt.savefig(target_path)
        sns.utils.despine()
        plt.close()

        fig, ax = plt.subplots()
        plt.bar(
            list(
                self.histogramReject.keys()), list(
                self.histogramReject.values()), width=1, color='r')
        if title is not None:
            plt.title(title)

        ax.set_xlabel("Rejected fragment size [bp]")
        ax.set_ylabel("# Fragments")
        plt.tight_layout()
        sns.utils.despine()
        plt.savefig(target_path.replace('.png', '.rejected.png'))
        plt.close()

        fig, ax = plt.subplots()
        ax.bar(
            list(
                self.histogramAccept.keys()), list(
                self.histogramAccept.values()), width=1, color='g')
        if title is not None:
            plt.title(title)


        ax.set_xlabel("Accepted fragment size [bp]")
        ax.set_ylabel("# Fragments")
        plt.tight_layout()
        sns.utils.despine()
        plt.savefig(target_path.replace('.png', '.accepted.png'))
        plt.close()


        fig, ax = plt.subplots()
        ax.bar(
            list(
                self.histogramMolecule.keys()), list(
                self.histogramMolecule.values()), width=1, color='g')
        if title is not None:
            plt.title(title)

        sns.utils.despine()
        ax.set_xlabel("Molecule size [bp]")
        ax.set_ylabel("# Molecules")
        plt.tight_layout()
        plt.savefig(target_path.replace('.png', '.molecules.png'))
        plt.close()
//  [python]
def barplot_messages_per_minutes(msgs, path_to_save, minutes=2):
    sns.set(style="whitegrid", palette="muted")
    sns.despine(top=True)

    messages_per_minutes = stools.get_messages_per_minutes(msgs, minutes)

    xticks_labels = stools.get_hours()
    xticks = [i * 60 // minutes for i in range(24)]

    min_minutes = len(min(messages_per_minutes.values(), key=lambda day: len(day)))
    max_minutes = len(max(messages_per_minutes.values(), key=lambda day: len(day)))
    pal = sns.color_palette("GnBu_d", max_minutes - min_minutes + 1)[::-1]

    ax = sns.barplot(x=list(range(len(messages_per_minutes))), y=[len(day) for day in messages_per_minutes.values()],
                     edgecolor="none",
                     palette=np.array(pal)[[len(day) - min_minutes for day in messages_per_minutes.values()]])
    _change_bar_width(ax, 1.)
    ax.set(xlabel="hour", ylabel="messages")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)

    fig = plt.gcf()
    fig.set_size_inches(20, 10)

    fig.savefig(os.path.join(path_to_save, barplot_messages_per_minutes.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{barplot_messages_per_minutes.__name__} was created.")
    plt.close("all")
//  [python]
def barplot_messages_per_minutes(msgs, path_to_save, minutes=2):
    sns.set(style="whitegrid", palette="muted")
    sns.utils.despine(top=True)

    messages_per_minutes = stools.get_messages_per_minutes(msgs, minutes)

    xticks_labels = stools.get_hours()
    xticks = [i * 60 // minutes for i in range(24)]

    min_minutes = len(min(messages_per_minutes.values(), key=lambda day: len(day)))
    max_minutes = len(max(messages_per_minutes.values(), key=lambda day: len(day)))
    pal = sns.color_palette("GnBu_d", max_minutes - min_minutes + 1)[::-1]

    ax = sns.barplot(x=list(range(len(messages_per_minutes))), y=[len(day) for day in messages_per_minutes.values()],
                     edgecolor="none",
                     palette=np.array(pal)[[len(day) - min_minutes for day in messages_per_minutes.values()]])
    _change_bar_width(ax, 1.)
    ax.set(xlabel="hour", ylabel="messages")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)

    fig = plt.gcf()
    fig.set_size_inches(20, 10)

    fig.savefig(os.path.join(path_to_save, barplot_messages_per_minutes.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{barplot_messages_per_minutes.__name__} was created.")
    plt.close("all")
//  [python]
def plot_summary(df, savename):

    fig, axs = plt.subplots(1, 3, figsize=(9, 3), sharex=True)

    ax = axs[0]
    plot_n_blocks_stats(df, ax)

    ax = axs[1]
    plot_block_len_stats(df, ax)

    ax = axs[2]
    plot_pangenome_size(df, ax)

    for i in range(3):
        add_panel_label(axs[i], i)

    # tweak second column ax
    ax.set_xscale("log")

    # despine and save
    sns.despine(fig)
    plt.tight_layout()
    plt.savefig(savename)
    plt.close(fig)
//  [python]
def plot_summary(df, savename):

    fig, axs = plt.subplots(1, 3, figsize=(9, 3), sharex=True)

    ax = axs[0]
    plot_n_blocks_stats(df, ax)

    ax = axs[1]
    plot_block_len_stats(df, ax)

    ax = axs[2]
    plot_pangenome_size(df, ax)

    for i in range(3):
        add_panel_label(axs[i], i)

    # tweak second column ax
    ax.set_xscale("log")

    # despine and save
    sns.utils.despine(fig)
    plt.tight_layout()
    plt.savefig(savename)
    plt.close(fig)
//  [python]
def barplot_messages_per_weekday(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid", palette="pastel")

    messages_per_weekday = stools.get_messages_per_weekday(msgs)
    labels = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

    ax = sns.barplot(x=labels, y=[len(weekday) for weekday in messages_per_weekday.values()],
                     label=your_name, color="b")
    sns.set_color_codes("muted")
    sns.barplot(x=labels,
                y=[len([msg for msg in weekday if msg.author == target_name])
                   for weekday in messages_per_weekday.values()],
                label=target_name, color="b")

    ax.legend(ncol=2, loc="lower right", frameon=True)
    ax.set(ylabel="messages")
    sns.despine(right=True, top=True)

    fig = plt.gcf()
    fig.set_size_inches(11, 8)

    fig.savefig(os.path.join(path_to_save, barplot_messages_per_weekday.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{barplot_messages_per_weekday.__name__} was created.")
    plt.close("all")
//  [python]
def barplot_messages_per_weekday(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid", palette="pastel")

    messages_per_weekday = stools.get_messages_per_weekday(msgs)
    labels = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

    ax = sns.barplot(x=labels, y=[len(weekday) for weekday in messages_per_weekday.values()],
                     label=your_name, color="b")
    sns.set_color_codes("muted")
    sns.barplot(x=labels,
                y=[len([msg for msg in weekday if msg.author == target_name])
                   for weekday in messages_per_weekday.values()],
                label=target_name, color="b")

    ax.legend(ncol=2, loc="lower right", frameon=True)
    ax.set(ylabel="messages")
    sns.utils.despine(right=True, top=True)

    fig = plt.gcf()
    fig.set_size_inches(11, 8)

    fig.savefig(os.path.join(path_to_save, barplot_messages_per_weekday.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{barplot_messages_per_weekday.__name__} was created.")
    plt.close("all")
//  [python]
def plot_all(df, savename):

    xvar = "n. genomes"
    variables = [
        "avg. fasta file size (Mb)",
        "avg. genome length (bp)",
        "n. core blocks",
        "n. blocks",
        "pangenome length (bp)",
        "avg. block length (bp)",
        "N50 (bp)",
        "L50",
        "F50",
        "fract. core pangenome",
        "len. core pangenome",
        "pangraph file size (Mb)",
        "avg. genome length (Mbp)",
        "filesize compression",
        "sequence compression",
        "pangenome length (Mbp)",
        "fract. core blocks",
        "fract. core genome",
    ]

    NV = len(variables)
    fig, axs = plt.subplots(1, NV, figsize=(NV * 3, 3), sharex=True)

    for nv, yvar in enumerate(variables):

        ax = axs[nv]
        sns.lineplot(
            ax=ax,
            data=df,
            x=xvar,
            y=yvar,
            ci="sd",
            marker=".",
            markeredgecolor=None,
        )
        ax.grid(alpha=0.2)
        ax.set_ylim(bottom=0)

    # tweak second column ax
    ax.set_xscale("log")

    # despine and save
    sns.despine(fig)
    plt.tight_layout()
    plt.savefig(savename)
    plt.close(fig)
//  [python]
def plot_all(df, savename):

    xvar = "n. genomes"
    variables = [
        "avg. fasta file size (Mb)",
        "avg. genome length (bp)",
        "n. core blocks",
        "n. blocks",
        "pangenome length (bp)",
        "avg. block length (bp)",
        "N50 (bp)",
        "L50",
        "F50",
        "fract. core pangenome",
        "len. core pangenome",
        "pangraph file size (Mb)",
        "avg. genome length (Mbp)",
        "filesize compression",
        "sequence compression",
        "pangenome length (Mbp)",
        "fract. core blocks",
        "fract. core genome",
    ]

    NV = len(variables)
    fig, axs = plt.subplots(1, NV, figsize=(NV * 3, 3), sharex=True)

    for nv, yvar in enumerate(variables):

        ax = axs[nv]
        sns.lineplot(
            ax=ax,
            data=df,
            x=xvar,
            y=yvar,
            ci="sd",
            marker=".",
            markeredgecolor=None,
        )
        ax.grid(alpha=0.2)
        ax.set_ylim(bottom=0)

    # tweak second column ax
    ax.set_xscale("log")

    # despine and save
    sns.utils.despine(fig)
    plt.tight_layout()
    plt.savefig(savename)
    plt.close(fig)
//  [python]
def ban_time(self):
        ind = Individual()
        res_list = ind.longest_ban()
        res_list = res_list[0:10]
        print(res_list)
        name_list = [i[1] for i in res_list]
        time_list = [i[2] for i in res_list]

        sns.set(style="darkgrid")
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
        f, ax = plt.subplots(figsize=(18.5, 9))

        # Plot the crashes where alcohol was involved
        sns.set_color_codes("muted")
        sns.barplot(x=time_list, y=name_list,
                    label="禁言时长", color="y")

        # Add a legend and informative axis label
        ax.legend(ncol=2, loc="lower right", frameon=True)
        ax.set(xlim=(0, time_list[0]), ylabel="",
               xlabel="禁言时间最长")
        sns.despine(left=True, bottom=True)

        plt.savefig('../photos/ban_time.png', format='png', dpi=400)
        plt.close()
//  [python]
def ban_time(self):
        ind = Individual()
        res_list = ind.longest_ban()
        res_list = res_list[0:10]
        print(res_list)
        name_list = [i[1] for i in res_list]
        time_list = [i[2] for i in res_list]

        sns.set(style="darkgrid")
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
        f, ax = plt.subplots(figsize=(18.5, 9))

        # Plot the crashes where alcohol was involved
        sns.set_color_codes("muted")
        sns.barplot(x=time_list, y=name_list,
                    label="禁言时长", color="y")

        # Add a legend and informative axis label
        ax.legend(ncol=2, loc="lower right", frameon=True)
        ax.set(xlim=(0, time_list[0]), ylabel="",
               xlabel="禁言时间最长")
        sns.utils.despine(left=True, bottom=True)

        plt.savefig('../photos/ban_time.png', format='png', dpi=400)
        plt.close()
//  [python]
times = [5,231,1244]
for ti in times:
    f, ax = plt.subplots(1,1,figsize=(5,5))
    sns.despine(bottom=True, left=True)
    sns.distplot(Z[:,ti],60,hist=True, kde=True, label=r'S$_\infty$',color=col_gr,ax=ax,kde_kws={"lw":"3","bw":'silverman'}, hist_kws=dict(edgecolor=None))
    sns.distplot(M[:,ti],60,hist=True, kde=True, label='D',color=col_ro,ax=ax,kde_kws={"lw":"3","bw":'silverman'}, hist_kws=dict(edgecolor=None))
    #sns.distplot(F1[:,ti],50,hist=True, kde=True, label='S',color='b')
    #plt.ylabel('%s'%labelss[di])
    plt.xlabel(r'$x$')     
    plt.ylabel(r'$\hat{P}(x)$')  
    if ti<200:
        plt.ylim([0,5.98])
    else:
        plt.ylim([0,0.98])
    plt.locator_params(axis='y', nbins=3)
    if ti<100:
        plt.legend(frameon=False,fontsize=20,loc=2) 
    plt.subplots_adjust(left=0.17,right=0.95,top=0.980)
    
    
#    if ti>101:
#           
#        axins = zoomed_inset_axes(ax, 2, loc=1)
#        sns.distplot(Z[:,ti],100,hist=True, kde=True, label=r'S$^\infty$',color=col_gr,ax=axins,kde_kws={"lw":"3"})
#        sns.distplot(M[:,ti],100,hist=True, kde=True, label='D',color=col_ro,ax=axins,kde_kws={"lw":"3"})
#        if ti== 3200:
#            x1, x2, y1, y2 = 1.1,1.3, 0.5, 1.5 # specify the limits # specify the limits
#        elif ti==101:
#            x1, x2, y1, y2 = 1.2,1.4, 0.3, 0.8
#        elif ti== 4400:
#            x1, x2, y1, y2 = 1.3,1.6, 0, 0.5
#        axins.set_xlim(x1, x2) # apply the x-limits
#        axins.set_ylim(y1, y2) # apply the y-limits
#        plt.yticks(visible=False)
#        plt.xticks(visible=False)
#        mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.2")
#    
#    axins2 = zoomed_inset_axes(ax, 2, loc=2)
#    sns.distplot(Z[:,ti],100,hist=True, kde=True, label=r'S$^\infty$',color=col_gr,ax=axins2,kde_kws={"lw":"3"})
#    sns.distplot(M[:,ti],100,hist=True, kde=True, label='D',color=col_ro,ax=axins2,kde_kws={"lw":"3"})
#    if ti== 3200:
#        x1, x2, y1, y2 = 0.35,0.6, 0., 0.5 # specify the limits # specify the limits
#    elif ti==101:
#        x1, x2, y1, y2 = 0.45,0.7, 0., 0.5
#    elif ti==4400:
#        x1, x2, y1, y2 = 0.35,0.6, 0., 0.5
#    axins2.set_xlim(x1, x2) # apply the x-limits
#    axins2.set_ylim(y1, y2) # apply the y-limits
#    plt.yticks(visible=False)
#    plt.xticks(visible=False)
#    mark_inset(ax, axins2, loc1=4, loc2=3, fc="none", ec="0.2")
    
    plt.savefig('DW_1D_dist_D_vs_S_ti%d_gg.pdf'%ti,  bbox_inches = 'tight', pad_inches = 0.05)     
    plt.savefig('DW_1D_dist_D_vs_S_ti%d_gg.png'%ti,  bbox_inches = 'tight', pad_inches = 0.05)
//  [python]
times = [5,231,1244]
for ti in times:
    f, ax = plt.subplots(1,1,figsize=(5,5))
    sns.utils.despine(bottom=True, left=True)
    sns.distplot(Z[:,ti],60,hist=True, kde=True, label=r'S$_\infty$',color=col_gr,ax=ax,kde_kws={"lw":"3","bw":'silverman'}, hist_kws=dict(edgecolor=None))
    sns.distplot(M[:,ti],60,hist=True, kde=True, label='D',color=col_ro,ax=ax,kde_kws={"lw":"3","bw":'silverman'}, hist_kws=dict(edgecolor=None))
    #sns.distplot(F1[:,ti],50,hist=True, kde=True, label='S',color='b')
    #plt.ylabel('%s'%labelss[di])
    plt.xlabel(r'$x$')     
    plt.ylabel(r'$\hat{P}(x)$')  
    if ti<200:
        plt.ylim([0,5.98])
    else:
        plt.ylim([0,0.98])
    plt.locator_params(axis='y', nbins=3)
    if ti<100:
        plt.legend(frameon=False,fontsize=20,loc=2) 
    plt.subplots_adjust(left=0.17,right=0.95,top=0.980)
    
    
#    if ti>101:
#           
#        axins = zoomed_inset_axes(ax, 2, loc=1)
#        sns.distplot(Z[:,ti],100,hist=True, kde=True, label=r'S$^\infty$',color=col_gr,ax=axins,kde_kws={"lw":"3"})
#        sns.distplot(M[:,ti],100,hist=True, kde=True, label='D',color=col_ro,ax=axins,kde_kws={"lw":"3"})
#        if ti== 3200:
#            x1, x2, y1, y2 = 1.1,1.3, 0.5, 1.5 # specify the limits # specify the limits
#        elif ti==101:
#            x1, x2, y1, y2 = 1.2,1.4, 0.3, 0.8
#        elif ti== 4400:
#            x1, x2, y1, y2 = 1.3,1.6, 0, 0.5
#        axins.set_xlim(x1, x2) # apply the x-limits
#        axins.set_ylim(y1, y2) # apply the y-limits
#        plt.yticks(visible=False)
#        plt.xticks(visible=False)
#        mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.2")
#    
#    axins2 = zoomed_inset_axes(ax, 2, loc=2)
#    sns.distplot(Z[:,ti],100,hist=True, kde=True, label=r'S$^\infty$',color=col_gr,ax=axins2,kde_kws={"lw":"3"})
#    sns.distplot(M[:,ti],100,hist=True, kde=True, label='D',color=col_ro,ax=axins2,kde_kws={"lw":"3"})
#    if ti== 3200:
#        x1, x2, y1, y2 = 0.35,0.6, 0., 0.5 # specify the limits # specify the limits
#    elif ti==101:
#        x1, x2, y1, y2 = 0.45,0.7, 0., 0.5
#    elif ti==4400:
#        x1, x2, y1, y2 = 0.35,0.6, 0., 0.5
#    axins2.set_xlim(x1, x2) # apply the x-limits
#    axins2.set_ylim(y1, y2) # apply the y-limits
#    plt.yticks(visible=False)
#    plt.xticks(visible=False)
#    mark_inset(ax, axins2, loc1=4, loc2=3, fc="none", ec="0.2")
    
    plt.savefig('DW_1D_dist_D_vs_S_ti%d_gg.pdf'%ti,  bbox_inches = 'tight', pad_inches = 0.05)     
    plt.savefig('DW_1D_dist_D_vs_S_ti%d_gg.png'%ti,  bbox_inches = 'tight', pad_inches = 0.05)
//  [python]
def speak_photo_in_total(self):
        """
        发言次数前10的用户及发送图片的比例
        :return:
        """
        ind = Individual()
        res_list = ind.most_speak('speak_num')
        res_list = res_list[0:10]
        print(res_list)
        ID_list = [i[0] for i in res_list]
        name_list = [i[1] for i in res_list]
        speak_list = [i[2] for i in res_list]
        photo_num = []
        for id in ID_list:
            for doc in self.post.find({'ID': id}, {'photo_num': 1}):
                photo_num.append(doc['photo_num'])
        sns.set(style="darkgrid")
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
        f, ax = plt.subplots(figsize=(18.5, 9))

        sns.set_color_codes("pastel")
        sns.barplot(x=speak_list, y=name_list,
                    label="发言次数", color="b")

        # Plot the crashes where alcohol was involved
        sns.set_color_codes("muted")
        sns.barplot(x=photo_num, y=name_list,
                    label="发送图片数", color="b")

        # Add a legend and informative axis label
        ax.legend(ncol=2, loc="lower right", frameon=True)
        ax.set(xlim=(0, speak_list[0]), ylabel="",
               xlabel="群里发言次数排行及发送图片的比例")
        sns.despine(left=True, bottom=True)

        plt.savefig('../photos/speak_photo_in_total.png', format='png', dpi=300)
        plt.close()
//  [python]
def speak_photo_in_total(self):
        """
        发言次数前10的用户及发送图片的比例
        :return:
        """
        ind = Individual()
        res_list = ind.most_speak('speak_num')
        res_list = res_list[0:10]
        print(res_list)
        ID_list = [i[0] for i in res_list]
        name_list = [i[1] for i in res_list]
        speak_list = [i[2] for i in res_list]
        photo_num = []
        for id in ID_list:
            for doc in self.post.find({'ID': id}, {'photo_num': 1}):
                photo_num.append(doc['photo_num'])
        sns.set(style="darkgrid")
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
        f, ax = plt.subplots(figsize=(18.5, 9))

        sns.set_color_codes("pastel")
        sns.barplot(x=speak_list, y=name_list,
                    label="发言次数", color="b")

        # Plot the crashes where alcohol was involved
        sns.set_color_codes("muted")
        sns.barplot(x=photo_num, y=name_list,
                    label="发送图片数", color="b")

        # Add a legend and informative axis label
        ax.legend(ncol=2, loc="lower right", frameon=True)
        ax.set(xlim=(0, speak_list[0]), ylabel="",
               xlabel="群里发言次数排行及发送图片的比例")
        sns.utils.despine(left=True, bottom=True)

        plt.savefig('../photos/speak_photo_in_total.png', format='png', dpi=300)
        plt.close()
//  [python]
def plot_resampling(X, y, sampler, ax):
    """Plot the resampled dataset using the sampler."""
    X_res, y_res = sampler.fit_resample(X, y)
    ax.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.8, edgecolor="k")
    sns.despine(ax=ax, offset=10)
    ax.set_title(f"Decision function for {sampler.__class__.__name__}")
    return Counter(y_res)
//  [python]
def plot_resampling(X, y, sampler, ax):
    """Plot the resampled dataset using the sampler."""
    X_res, y_res = sampler.fit_resample(X, y)
    ax.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.8, edgecolor="k")
    sns.utils.despine(ax=ax, offset=10)
    ax.set_title(f"Decision function for {sampler.__class__.__name__}")
    return Counter(y_res)
//  [python]
def plot_elbo(self):
        """
        Plot the ELBO values after running ADVI minibatch.
        """
        sns.set_style("white")
        plt.plot(-self.advi_hist)
        plt.ylabel('ELBO')
        plt.xlabel('iteration')
        sns.despine()
//  [python]
def plot_elbo(self):
        """
        Plot the ELBO values after running ADVI minibatch.
        """
        sns.set_style("white")
        plt.plot(-self.advi_hist)
        plt.ylabel('ELBO')
        plt.xlabel('iteration')
        sns.utils.despine()
//  [python]
def get_quizes_plot(quizes):
    fig, ax = plt.subplots()
    ax.xaxis.set_major_formatter(dates_fmt)
    for type_ in ('hars', 'madrs'):
        x = [datetime.strptime(quiz.created_at, '%Y-%m-%d %H-%M-%S') for quiz in quizes if quiz.type_ == type_]
        y = [quiz.result for quiz in quizes if quiz.type_ == type_]
        ax.plot(x, y, label=type_.upper())
    ax.legend()
    sns.despine()
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    return buf
//  [python]
def get_quizes_plot(quizes):
    fig, ax = plt.subplots()
    ax.xaxis.set_major_formatter(dates_fmt)
    for type_ in ('hars', 'madrs'):
        x = [datetime.strptime(quiz.created_at, '%Y-%m-%d %H-%M-%S') for quiz in quizes if quiz.type_ == type_]
        y = [quiz.result for quiz in quizes if quiz.type_ == type_]
        ax.plot(x, y, label=type_.upper())
    ax.legend()
    sns.utils.despine()
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    return buf
//  [python]
def plot_negative_correlations(df: pd.DataFrame) -> matplotlib.figure.Figure:
    figure = plt.figure(figsize=(21, 12))

    plt.subplot(3, 1, 1)
    sns.regplot(
        x=df["Platelets"], y=df["Stage"], scatter=False, logistic=False, color="orchid"
    )
    sns.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(plt.title("Cirrhosis Probability with Platelets"), color="darkmagenta")

    plt.subplot(3, 1, 2)
    sns.regplot(
        x=df["Albumin"], y=df["Stage"], scatter=False, logistic=False, color="royalblue"
    )
    sns.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(plt.title("Cirrhosis Probability with Albumin Content"), color="royalblue")

    plt.subplot(3, 1, 3)
    sns.regplot(
        x=df["Cholesterol"],
        y=df["Stage"],
        scatter=False,
        logistic=False,
        color="orchid",
    )
    sns.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(plt.title("Cirrhosis Probability Cholesterol"), color="darkmagenta")

    return figure
//  [python]
def plot_negative_correlations(df: pd.DataFrame) -> matplotlib.figure.Figure:
    figure = plt.figure(figsize=(21, 12))

    plt.subplot(3, 1, 1)
    sns.regplot(
        x=df["Platelets"], y=df["Stage"], scatter=False, logistic=False, color="orchid"
    )
    sns.utils.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(plt.title("Cirrhosis Probability with Platelets"), color="darkmagenta")

    plt.subplot(3, 1, 2)
    sns.regplot(
        x=df["Albumin"], y=df["Stage"], scatter=False, logistic=False, color="royalblue"
    )
    sns.utils.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(plt.title("Cirrhosis Probability with Albumin Content"), color="royalblue")

    plt.subplot(3, 1, 3)
    sns.regplot(
        x=df["Cholesterol"],
        y=df["Stage"],
        scatter=False,
        logistic=False,
        color="orchid",
    )
    sns.utils.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(plt.title("Cirrhosis Probability Cholesterol"), color="darkmagenta")

    return figure
//  [python]
def plot_positive_correlations(df: pd.DataFrame) -> matplotlib.figure.Figure:
    figure = plt.figure(figsize=(21, 12))

    plt.subplot(3, 1, 1)
    sns.regplot(
        x=df["Age"], y=df["Stage"], scatter=False, logistic=False, color="royalblue"
    )
    sns.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(
        plt.title("Cirrhosis Probability with increasing Age(in days)"),
        color="royalblue",
    )

    plt.subplot(3, 1, 2)
    sns.regplot(
        x=df["Prothrombin"],
        y=df["Stage"],
        scatter=False,
        logistic=False,
        color="orchid",
    )
    sns.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(
        plt.title("Cirrhosis Probability with increasing Prothrombin Content"),
        color="darkmagenta",
    )

    plt.subplot(3, 1, 3)
    sns.regplot(
        x=df["Copper"], y=df["Stage"], scatter=False, logistic=False, color="royalblue"
    )
    sns.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(
        plt.title("Cirrhosis Probability with increasing Copper Accumulation"),
        color="royalblue",
    )

    return figure
//  [python]
def plot_positive_correlations(df: pd.DataFrame) -> matplotlib.figure.Figure:
    figure = plt.figure(figsize=(21, 12))

    plt.subplot(3, 1, 1)
    sns.regplot(
        x=df["Age"], y=df["Stage"], scatter=False, logistic=False, color="royalblue"
    )
    sns.utils.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(
        plt.title("Cirrhosis Probability with increasing Age(in days)"),
        color="royalblue",
    )

    plt.subplot(3, 1, 2)
    sns.regplot(
        x=df["Prothrombin"],
        y=df["Stage"],
        scatter=False,
        logistic=False,
        color="orchid",
    )
    sns.utils.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(
        plt.title("Cirrhosis Probability with increasing Prothrombin Content"),
        color="darkmagenta",
    )

    plt.subplot(3, 1, 3)
    sns.regplot(
        x=df["Copper"], y=df["Stage"], scatter=False, logistic=False, color="royalblue"
    )
    sns.utils.despine(
        fig=None,
        ax=None,
        top=True,
        right=True,
        left=True,
        bottom=True,
        offset=None,
        trim=False,
    )
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.ylabel("Cirrhosis Probability")
    plt.setp(
        plt.title("Cirrhosis Probability with increasing Copper Accumulation"),
        color="royalblue",
    )

    return figure
//  [python]
def plot_disease_across_features(df: pd.DataFrame) -> matplotlib.figure.Figure:
    figure = plt.figure(figsize=(21.2, 10))

    plt.subplot(2, 3, 1)
    sns.countplot(data=df, x="Stage", hue="Sex", palette="Blues", alpha=0.9)
    sns.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Disease Stage Across Gender")

    plt.subplot(2, 3, 2)
    sns.countplot(data=df, x="Stage", hue="Ascites", palette="Purples", alpha=0.9)
    sns.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Ascites proportion across Stages")

    plt.subplot(2, 3, 3)
    sns.countplot(data=df, x="Stage", hue="Drug", palette="Blues", alpha=0.9)
    sns.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Medications prescribed across Stages")

    plt.subplot(2, 3, 4)
    sns.countplot(data=df, x="Stage", hue="Hepatomegaly", palette="Purples", alpha=0.9)
    sns.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Hepatomegaly")

    plt.subplot(2, 3, 5)
    sns.countplot(data=df, x="Stage", hue="Spiders", palette="Blues", alpha=0.9)
    sns.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Presence of Spiders across stages")

    plt.subplot(2, 3, 6)
    sns.countplot(data=df, x="Stage", hue="Edema", palette="Purples", alpha=0.9)
    sns.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Edema")

    return figure
//  [python]
def plot_disease_across_features(df: pd.DataFrame) -> matplotlib.figure.Figure:
    figure = plt.figure(figsize=(21.2, 10))

    plt.subplot(2, 3, 1)
    sns.countplot(data=df, x="Stage", hue="Sex", palette="Blues", alpha=0.9)
    sns.utils.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Disease Stage Across Gender")

    plt.subplot(2, 3, 2)
    sns.countplot(data=df, x="Stage", hue="Ascites", palette="Purples", alpha=0.9)
    sns.utils.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Ascites proportion across Stages")

    plt.subplot(2, 3, 3)
    sns.countplot(data=df, x="Stage", hue="Drug", palette="Blues", alpha=0.9)
    sns.utils.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Medications prescribed across Stages")

    plt.subplot(2, 3, 4)
    sns.countplot(data=df, x="Stage", hue="Hepatomegaly", palette="Purples", alpha=0.9)
    sns.utils.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Hepatomegaly")

    plt.subplot(2, 3, 5)
    sns.countplot(data=df, x="Stage", hue="Spiders", palette="Blues", alpha=0.9)
    sns.utils.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Presence of Spiders across stages")

    plt.subplot(2, 3, 6)
    sns.countplot(data=df, x="Stage", hue="Edema", palette="Purples", alpha=0.9)
    sns.utils.despine(top=True, right=True, bottom=True, left=True)
    plt.tick_params(axis="both", which="both", bottom=False, top=False, left=False)
    plt.xlabel("")
    plt.title("Edema")

    return figure
//  [python]
def plot_discovered_occurred_ratio_range(dataframe, file_path=''):
  """Plot the range of discovered incidents/occurred range between locations."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.set_style('whitegrid')
  sns.despine()

  sns.catplot(
      x='param_value',
      y='discovered/occurred range',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred range', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '.pdf', bbox_inches='tight')

  sns.catplot(
      x='param_value',
      y='discovered/occurred range weighted',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Delta', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_weighted.pdf', bbox_inches='tight')
//  [python]
def plot_discovered_occurred_ratio_range(dataframe, file_path=''):
  """Plot the range of discovered incidents/occurred range between locations."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.set_style('whitegrid')
  sns.utils.despine()

  sns.catplot(
      x='param_value',
      y='discovered/occurred range',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred range', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '.pdf', bbox_inches='tight')

  sns.catplot(
      x='param_value',
      y='discovered/occurred range weighted',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Delta', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_weighted.pdf', bbox_inches='tight')
//  [python]
def plot_total_miss_discovered(dataframe, file_path=''):
  """Plot bar charts comparing agents total missed and discovered incidents."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.set_style('whitegrid')
  sns.despine()

  sns.catplot(
      x='param_value',
      y='total_missed',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Total missed incidents', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_missed.pdf', bbox_inches='tight')

  sns.catplot(
      x='param_value',
      y='total_discovered',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Total discovered incidents', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_discovered.pdf', bbox_inches='tight')
//  [python]
def plot_total_miss_discovered(dataframe, file_path=''):
  """Plot bar charts comparing agents total missed and discovered incidents."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.set_style('whitegrid')
  sns.utils.despine()

  sns.catplot(
      x='param_value',
      y='total_missed',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Total missed incidents', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_missed.pdf', bbox_inches='tight')

  sns.catplot(
      x='param_value',
      y='total_discovered',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Total discovered incidents', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_discovered.pdf', bbox_inches='tight')
//  [python]
ax = plt.subplot(111)
sns.scatterplot(
    data=emp_scores,
    x='connectome',
    y='z-score',
    s=30,
    c='black',
    ax=ax
)
sns.stripplot(
    data=null_scores,
    x='connectome',
    y='z-score',
    # width=0.5,
    s=2.5,
    jitter=0.3,
    ax=ax
)
ax.set_ylim(-2.5, 12.5)
sns.despine(offset=10, trim=True,
            top=True, bottom=False,
            right=True, left=False)