jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def visualize_bitrate_smoothed(allInfos):
    plt.figure(figsize=FIGSIZE.WIDE_M)
    sns.set(style="ticks", palette=PALETTE_5)

    data = {
        'segment': [],
        'bitrate': [],
        'config': [],
    }

    bitrates = set()

    for conf, infos in allInfos.items():
        config = fixname(f"{conf.scheduler} - {conf.fec}".upper())
        for info in infos:
            for i in range(len(info.segment_bitrates)):
                if i < 2 or i >= len(info.segment_bitrates) - 2:
                    continue

                neighbour_bitrates = [
                    info.segment_bitrates[i-2]//10**6,
                    info.segment_bitrates[i-1]//10**6,
                    info.segment_bitrates[i]//10**6,
                    info.segment_bitrates[i+1]//10**6,
                    info.segment_bitrates[i+2]//10**6,
                ]
                data['segment'].append(i)
                data['bitrate'].append(get_mean(neighbour_bitrates))
                data['config'].append(config)
                bitrates.add(info.segment_bitrates[i]//10**6)

    df = pandas.DataFrame.from_dict(data)
    ax = sns.tsplot(data=df, time='segment', value='bitrate', unit='config',
                      palette='muted')

    ax.set(xlabel='Segment Number', ylabel='Bit Rate (Mbit/s)')
    plt.yticks(list(bitrates))
    ax.ticklabel_format(style='plain')
    plt.savefig("vis-abr-smooth." + FORMAT)
//  [python]
def visualize_bitrate_smoothed(allInfos):
    plt.figure(figsize=FIGSIZE.WIDE_M)
    sns.set(style="ticks", palette=PALETTE_5)

    data = {
        'segment': [],
        'bitrate': [],
        'config': [],
    }

    bitrates = set()

    for conf, infos in allInfos.items():
        config = fixname(f"{conf.scheduler} - {conf.fec}".upper())
        for info in infos:
            for i in range(len(info.segment_bitrates)):
                if i < 2 or i >= len(info.segment_bitrates) - 2:
                    continue

                neighbour_bitrates = [
                    info.segment_bitrates[i-2]//10**6,
                    info.segment_bitrates[i-1]//10**6,
                    info.segment_bitrates[i]//10**6,
                    info.segment_bitrates[i+1]//10**6,
                    info.segment_bitrates[i+2]//10**6,
                ]
                data['segment'].append(i)
                data['bitrate'].append(get_mean(neighbour_bitrates))
                data['config'].append(config)
                bitrates.add(info.segment_bitrates[i]//10**6)

    df = pandas.DataFrame.from_dict(data)
    ax = sns.lineplot(data=df, x='segment', y='bitrate', hue='config',
                      palette='muted')

    ax.set(xlabel='Segment Number', ylabel='Bit Rate (Mbit/s)')
    plt.yticks(list(bitrates))
    ax.ticklabel_format(style='plain')
    plt.savefig("vis-abr-smooth." + FORMAT)
//  [python]
def plot(df, end_time, figname, x="time", y="pct", hue="Task"):
    fig, ax = plt.subplots(figsize=figsize)
    g = sns.tsplot(data=df, time=x, value=y, unit="Task", ax=ax)
    plt.axvline(
        end_time,
        figure=fig,
        color="gray",
        linestyle="-",
        label="theoretical",
    )
    #    plt.fill_between(df[x].values, df[y].values, alpha=0.1)
    plt.xlim((0, int(math.ceil(end_time))))
    plt.ylim((0, 100))
    ax.yaxis.set_major_formatter(mpl.ticker.PercentFormatter(decimals=0))
    plt.xlabel("Time (s)")
    plt.ylabel("% Tasks completed")
    plt.grid(axis="y")
    filename = figname + ".pdf"
    print(filename)
    plt.savefig(filename, bbox_inches="tight")
//  [python]
def plot(df, end_time, figname, x="time", y="pct", hue="Task"):
    fig, ax = plt.subplots(figsize=figsize)
    g = sns.lineplot(data=df, x=x, y=y, hue=hue, ax=ax)
    plt.axvline(
        end_time,
        figure=fig,
        color="gray",
        linestyle="-",
        label="theoretical",
    )
    #    plt.fill_between(df[x].values, df[y].values, alpha=0.1)
    plt.xlim((0, int(math.ceil(end_time))))
    plt.ylim((0, 100))
    ax.yaxis.set_major_formatter(mpl.ticker.PercentFormatter(decimals=0))
    plt.xlabel("Time (s)")
    plt.ylabel("% Tasks completed")
    plt.grid(axis="y")
    filename = figname + ".pdf"
    print(filename)
    plt.savefig(filename, bbox_inches="tight")
//  [python]
sol['time'] /= 1.475e-5

ax = analytical.plot(style='.', x='time', y='analytical',
                     c='black', marker='+', ms=7)
sns.set_style("ticks")
plicRDF = sol[sol['interfaceType'] == 'plicRDF']
ax = sns.tsplot(x='time', y='max', hue='Method', style="nCells", data=plicRDF,
                  hue_order=['gradAlpha', 'fitParaboloid', 'RDF'], ax=ax)
//  [python]
sol['time'] /= 1.475e-5

ax = analytical.plot(style='.', x='time', y='analytical',
                     c='black', marker='+', ms=7)
sns.set_style("ticks")
plicRDF = sol[sol['interfaceType'] == 'plicRDF']
ax = sns.lineplot(x='time', y='max', hue='Method', style="nCells", data=plicRDF,
                  hue_order=['gradAlpha', 'fitParaboloid', 'RDF'], ax=ax)
//  [python]
sns.set(style="whitegrid")
sns.set_context("paper", font_scale=0.4 , rc={"lines.linewidth": 2.0})

mem = '0'
counter=0
for dd in data:
    temp_data = {}
    for a in dd:
        # print(a)
        if a[0] in temp_data:
            if mem in a[1]:
                temp_data[a[0]].append(a[1][mem][0])
            else:
                temp_data[a[0]].append(a[1]['100'][0])
            # print(temp_data)
        else:
            temp_data[a[0]] = []
    d = temp_data
    # print(results_dict[folder])
    df = pd.DataFrame(d).T
    df['#Classes'] = df.index
    # print(df)
    # print(df.columns)
    # df = pd.DataFrame.from_dict(results_dict[folder], orient='index')
    # df['Episode'] = df.index
    df = df.melt('#Classes', var_name='cols', value_name='Accuracy')
    # print(df)
    # # print(df['vals'])
    # plt.ylim(0, 1)
    print(folders[counter])
    plt.plot(df['#Classes'],df['Accuracy'], label =folders[counter])
    counter+=1
//  [python]
sns.set(style="whitegrid")
sns.set_context("paper", font_scale=0.4 , rc={"lines.linewidth": 2.0})

mem = '0'
counter=0
for dd in data:
    temp_data = {}
    for a in dd:
        # print(a)
        if a[0] in temp_data:
            if mem in a[1]:
                temp_data[a[0]].append(a[1][mem][0])
            else:
                temp_data[a[0]].append(a[1]['100'][0])
            # print(temp_data)
        else:
            temp_data[a[0]] = []
    d = temp_data
    # print(results_dict[folder])
    df = pd.DataFrame(d).T
    df['#Classes'] = df.index
    # print(df)
    # print(df.columns)
    # df = pd.DataFrame.from_dict(results_dict[folder], orient='index')
    # df['Episode'] = df.index
    df = df.melt('#Classes', var_name='cols', value_name='Accuracy')
    # print(df)
    # # print(df['vals'])
    # plt.ylim(0, 1)
    print(folders[counter])
    sns.lineplot(x='#Classes', y='Accuracy', data=df, legend='full',label =folders[counter])
    counter+=1
//  [python]
clx = {"RT": "red", "MT": "green", "RE": "blue"}

plt.subplot(1, 1, 1)
plt.title("Temporal edge dynamics")
slices = []
for k, v in num_edges.items():
    plt.plot(list(range(len(v))), v, label=k, color=clx[k])
//  [python]
clx = {"RT": "red", "MT": "green", "RE": "blue"}

plt.subplot(1, 1, 1)
plt.title("Temporal edge dynamics")
slices = []
for k, v in num_edges.items():
    sns.lineplot(list(range(len(v))), v, label=k, color=clx[k])
//  [python]
def get_fig(use_dark):
    
    d = pd.DataFrame()
    for lang in langs:
        d[lang] = pd.read_csv(f"ngrams/1grams_{lang}.csv",
                              usecols=['cumshare'], nrows=10000)

    d.index = range(1, len(d)+1)
    d.columns = langnames

    plt.clf()
    matplotlib.rcParams.update(matplotlib.rcParamsDefault)
    sns.set_theme(style="whitegrid")
    plt.rcParams.update({"grid.linewidth":0.5, "grid.alpha":0.6})
    
    if use_dark:
        plt.style.use("dark_background")
        light_or_dark = "dark"
    else:
        light_or_dark = "light"
        
    plot = sns.tsplot(data=d, palette="tab10", linewidth=1)
    plot.legend(bbox_to_anchor=(0.001, 1.0), loc="upper left")
    plot.set_xlabel("Most common words learned")
    plot.set_ylabel("% words in a typical book one can understand")
    plot.set(xscale="log")
    plot.get_xaxis().set_major_formatter(ScalarFormatter())
    plot.get_yaxis().set_major_formatter(PercentFormatter(xmax=1.0, symbol=''))
    plt.xlim(1, 10000)
    plt.ylim(0, 1)
    plt.savefig(f"graph_1grams_cumshare_rank_{light_or_dark}.svg")
//  [python]
def get_fig(use_dark):
    
    d = pd.DataFrame()
    for lang in langs:
        d[lang] = pd.read_csv(f"ngrams/1grams_{lang}.csv",
                              usecols=['cumshare'], nrows=10000)

    d.index = range(1, len(d)+1)
    d.columns = langnames

    plt.clf()
    matplotlib.rcParams.update(matplotlib.rcParamsDefault)
    sns.set_theme(style="whitegrid")
    plt.rcParams.update({"grid.linewidth":0.5, "grid.alpha":0.6})
    
    if use_dark:
        plt.style.use("dark_background")
        light_or_dark = "dark"
    else:
        light_or_dark = "light"
        
    plot = sns.lineplot(data=d, palette="tab10", linewidth=1)
    plot.legend(bbox_to_anchor=(0.001, 1.0), loc="upper left")
    plot.set_xlabel("Most common words learned")
    plot.set_ylabel("% words in a typical book one can understand")
    plot.set(xscale="log")
    plot.get_xaxis().set_major_formatter(ScalarFormatter())
    plot.get_yaxis().set_major_formatter(PercentFormatter(xmax=1.0, symbol=''))
    plt.xlim(1, 10000)
    plt.ylim(0, 1)
    plt.savefig(f"graph_1grams_cumshare_rank_{light_or_dark}.svg")
//  [python]
plt.subplots_adjust(wspace=0.1, hspace=0.1)
plt.suptitle('Suffix Array Distributions', fontsize=16, y = .94, fontweight='heavy')
minys = []
maxys = []
for fileindex in range(0, len(fns)):
  fn = fns[fileindex]
  name = names[fileindex]
  shortname = shortnames[fileindex]
  xs = []
  ys = []
  with open(fn) as f:
    for line in f:
      tokens = line.split()
      xs.append(int(tokens[1]))
      ys.append(int(tokens[2]))
  minys.append(min(ys))
  maxys.append(max(ys))
  plot = sns.tsplot(xs, ys, color = 'rebeccapurple', ax = axs[fileindex/3][fileindex%3])
  if fileindex / 3 == 1:
    plot.set_xlabel('k-mer', fontsize=14)
  if fileindex%3 == 0:
    plot.set_ylabel('Suffix Array Position', fontsize=14)
  plot.set_title(name, fontsize=16)
  axs[fileindex/3][fileindex%3].set_yticklabels([])
  axs[fileindex/3][fileindex%3].set_xticklabels([])
//  [python]
plt.subplots_adjust(wspace=0.1, hspace=0.1)
plt.suptitle('Suffix Array Distributions', fontsize=16, y = .94, fontweight='heavy')
minys = []
maxys = []
for fileindex in range(0, len(fns)):
  fn = fns[fileindex]
  name = names[fileindex]
  shortname = shortnames[fileindex]
  xs = []
  ys = []
  with open(fn) as f:
    for line in f:
      tokens = line.split()
      xs.append(int(tokens[1]))
      ys.append(int(tokens[2]))
  minys.append(min(ys))
  maxys.append(max(ys))
  plot = sns.lineplot(xs, ys, color = 'rebeccapurple', ax = axs[fileindex/3][fileindex%3])
  if fileindex / 3 == 1:
    plot.set_xlabel('k-mer', fontsize=14)
  if fileindex%3 == 0:
    plot.set_ylabel('Suffix Array Position', fontsize=14)
  plot.set_title(name, fontsize=16)
  axs[fileindex/3][fileindex%3].set_yticklabels([])
  axs[fileindex/3][fileindex%3].set_xticklabels([])
//  [python]
sns.set_style(style='darkgrid')


# Plots the evolution of expected cumulative regrets curves,
# for all tested policies and over all rounds
if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("--data_path", type=str, default="results.json", required=False,
                        help="path to data")

    args = parser.parse_args()

    with open(args.data_path, 'r') as fp:
        cumulative_regrets = json.load(fp)

    for k,v in cumulative_regrets.items():
        plt.plot(np.array(v), label=k)
    plt.xlabel("Round")
    plt.ylabel("Cumulative Regret")
    plt.show()
//  [python]
sns.set_style(style='darkgrid')


# Plots the evolution of expected cumulative regrets curves,
# for all tested policies and over all rounds
if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("--data_path", type=str, default="results.json", required=False,
                        help="path to data")

    args = parser.parse_args()

    with open(args.data_path, 'r') as fp:
        cumulative_regrets = json.load(fp)

    for k,v in cumulative_regrets.items():
        sns.lineplot(data = np.array(v), label=k)
    plt.xlabel("Round")
    plt.ylabel("Cumulative Regret")
    plt.show()
//  [python]
indivdual_candle_stats = [candle_optimizer(df= bulls, candle_name=candle) for candle in bull_candle_names] 

#Optimize by profits
#Plot of avg movement + distribution

for i, n in zip(indivdual_candle_stats, bull_candle_names):
    i.reindex(sorted(i), axis=1)
    i['most_returns'] = i.sum(axis=1)/len(i.columns)
    amount = str(i["most_returns"].max())
    what_day = i["most_returns"].idxmax()
    print('For candle ' + n + ', period ' + what_day + ' is the best day to get out giving an average of ' + amount + ' points')
    plt.figure()
    sns.tsplot(data=i["most_returns"], legend='full').set_title(n)
    sns.distplot(data=i["most_returns"], kde=True)
    plt.show()
//  [python]
indivdual_candle_stats = [candle_optimizer(df= bulls, candle_name=candle) for candle in bull_candle_names] 

#Optimize by profits
#Plot of avg movement + distribution

for i, n in zip(indivdual_candle_stats, bull_candle_names):
    i.reindex(sorted(i), axis=1)
    i['most_returns'] = i.sum(axis=1)/len(i.columns)
    amount = str(i["most_returns"].max())
    what_day = i["most_returns"].idxmax()
    print('For candle ' + n + ', period ' + what_day + ' is the best day to get out giving an average of ' + amount + ' points')
    plt.figure()
    sns.lineplot(data=i["most_returns"], legend='full').set_title(n)
    sns.displot(data=i["most_returns"], kind='kde')
    plt.show()
//  [python]
def plot_data(base_dir, data):
  """Plot the data collected from all experiment runs."""
  df = pd.DataFrame(data=data)
  for error in ['max_error_q', 'avg_error_q']:
    plt.subplots(1, 1, figsize=(8, 6))
    sns.tsplot(x='num_known_states', y=error, hue='Metric', data=df,
                 ci=99, lw=3)
    plt.xlabel('Number of known states', fontsize=24)
    ylabel = r'$L_{\infty}$ Error' if error == 'max_error' else 'Avg. Error'
    plt.ylabel(ylabel, fontsize=24)
    plt.legend(fontsize=18)
    pdf_file = os.path.join(base_dir,
                            'subsampled_value_iteration_{}.pdf'.format(error))
    with tf.gfile.GFile(pdf_file, 'w') as f:
      plt.savefig(f, format='pdf', dpi=300, bbox_inches='tight')
    plt.clf()
    plt.close('all')
//  [python]
def plot_data(base_dir, data):
  """Plot the data collected from all experiment runs."""
  df = pd.DataFrame(data=data)
  for error in ['max_error_q', 'avg_error_q']:
    plt.subplots(1, 1, figsize=(8, 6))
    sns.lineplot(x='num_known_states', y=error, hue='Metric', data=df,
                 ci=99, lw=3)
    plt.xlabel('Number of known states', fontsize=24)
    ylabel = r'$L_{\infty}$ Error' if error == 'max_error' else 'Avg. Error'
    plt.ylabel(ylabel, fontsize=24)
    plt.legend(fontsize=18)
    pdf_file = os.path.join(base_dir,
                            'subsampled_value_iteration_{}.pdf'.format(error))
    with tf.gfile.GFile(pdf_file, 'w') as f:
      plt.savefig(f, format='pdf', dpi=300, bbox_inches='tight')
    plt.clf()
    plt.close('all')
//  [python]
def plot_data(base_dir, data):
  """Plot the data collected from all experiment runs."""
  del data['qg']
  del data['exact_qvalues']
  df = pd.DataFrame(data=data)
  plt.subplots(1, 1, figsize=(8, 6))
  sns.tsplot(x='num_states_target', y='error', hue='Metric', data=df,
               ci=99, lw=3)
  plt.xlabel('Number of aggregate states', fontsize=24)
  plt.ylabel('Avg. Error', fontsize=24)
  plt.legend(fontsize=18)
  pdf_file = os.path.join(base_dir, 'aggregate_value_iteration.pdf')
  with tf.io.gfile.GFile(pdf_file, 'w') as f:
    plt.savefig(f, format='pdf', dpi=300, bbox_inches='tight')
  plt.clf()
  plt.close('all')
//  [python]
def plot_data(base_dir, data):
  """Plot the data collected from all experiment runs."""
  del data['qg']
  del data['exact_qvalues']
  df = pd.DataFrame(data=data)
  plt.subplots(1, 1, figsize=(8, 6))
  sns.lineplot(x='num_states_target', y='error', hue='Metric', data=df,
               ci=99, lw=3)
  plt.xlabel('Number of aggregate states', fontsize=24)
  plt.ylabel('Avg. Error', fontsize=24)
  plt.legend(fontsize=18)
  pdf_file = os.path.join(base_dir, 'aggregate_value_iteration.pdf')
  with tf.io.gfile.GFile(pdf_file, 'w') as f:
    plt.savefig(f, format='pdf', dpi=300, bbox_inches='tight')
  plt.clf()
  plt.close('all')
//  [python]
def create_eval_rank_vs_sc_plot(ws_scores, out_plot,
                                x_label="site rank",
                                y_label="whole-site score",
                                theme=1):
    """
    Plot rank of whole-site score (x-axis) vs score (y-axis).

    """
    assert ws_scores, "ws_scores empty"
    data = {'score': [], 'rank' : []}
    #ws_scores.sort(reverse=True)
    i = 0
    for sc in sorted(ws_scores, reverse=True):
        rank = i + 1
        data['score'].append(sc)
        data['rank'].append(rank)
        i += 1

    df = pd.DataFrame (data, columns = ['score', 'rank'])

    if theme == 1:
        # Make plot.
        sns.set(style="darkgrid")
        fig, ax = plt.subplots()
        sns.plt.plot(df['rank'], df['score'], color='#69e9f6')
        fig.set_figwidth(6)
        fig.set_figheight(4)
        ax.set(xlabel=x_label)
        ax.set_ylabel(y_label)
        #ax.tick_params(axis='x', labelsize=18)
        #ax.tick_params(axis='y', labelsize=14)
        fig.savefig(out_plot, dpi=150, bbox_inches='tight')

    elif theme == 2:
        text_color = "#fcc826"
        plot_color = "#fd3b9d"
        box_color = "#2f19f3"
        # Make plot.
        sns.set(style="darkgrid", rc={ "axes.labelcolor": text_color, "text.color": text_color, "xtick.color": text_color, "ytick.color": text_color, "grid.color": plot_color, "axes.edgecolor": plot_color})
        fig, ax = plt.subplots()
        sns.plt.plot(df['rank'], df['score'], color='blue')
        fig.set_figwidth(6)
        fig.set_figheight(4)
        ax.set(xlabel=x_label)
        ax.set_ylabel(y_label)
        #ax.tick_params(axis='x', labelsize=18)
        #ax.tick_params(axis='y', labelsize=14)
        fig.savefig(out_plot, dpi=150, bbox_inches='tight', transparent=True)
//  [python]
def create_eval_rank_vs_sc_plot(ws_scores, out_plot,
                                x_label="site rank",
                                y_label="whole-site score",
                                theme=1):
    """
    Plot rank of whole-site score (x-axis) vs score (y-axis).

    """
    assert ws_scores, "ws_scores empty"
    data = {'score': [], 'rank' : []}
    #ws_scores.sort(reverse=True)
    i = 0
    for sc in sorted(ws_scores, reverse=True):
        rank = i + 1
        data['score'].append(sc)
        data['rank'].append(rank)
        i += 1

    df = pd.DataFrame (data, columns = ['score', 'rank'])

    if theme == 1:
        # Make plot.
        sns.set(style="darkgrid")
        fig, ax = plt.subplots()
        sns.lineplot(data=df, x='rank', y='score', color='#69e9f6')
        fig.set_figwidth(6)
        fig.set_figheight(4)
        ax.set(xlabel=x_label)
        ax.set_ylabel(y_label)
        #ax.tick_params(axis='x', labelsize=18)
        #ax.tick_params(axis='y', labelsize=14)
        fig.savefig(out_plot, dpi=150, bbox_inches='tight')

    elif theme == 2:
        text_color = "#fcc826"
        plot_color = "#fd3b9d"
        box_color = "#2f19f3"
        # Make plot.
        sns.set(style="darkgrid", rc={ "axes.labelcolor": text_color, "text.color": text_color, "xtick.color": text_color, "ytick.color": text_color, "grid.color": plot_color, "axes.edgecolor": plot_color})
        fig, ax = plt.subplots()
        sns.lineplot(data=df, x='rank', y='score', color='blue')
        fig.set_figwidth(6)
        fig.set_figheight(4)
        ax.set(xlabel=x_label)
        ax.set_ylabel(y_label)
        #ax.tick_params(axis='x', labelsize=18)
        #ax.tick_params(axis='y', labelsize=14)
        fig.savefig(out_plot, dpi=150, bbox_inches='tight', transparent=True)
//  [python]
out_dir = "/network/scratch/x/xu.ji/mutual_info/v6c"

r = torch.load(os.path.join(out_dir, "results_%d.pt" % model_ind))

fig, axarr = plt.subplots(1, figsize=(4, 1 * 4))
l_MIs = r["diagnostics"]["l_MIs"]
axarr.plot(r["diagnostics"]["l_MIs"])
#sns.lineplot(x=range(len(l_MIs)), y=l_MIs, palette="deep", ax=axarr)
//  [python]
out_dir = "/network/scratch/x/xu.ji/mutual_info/v6c"

r = torch.load(os.path.join(out_dir, "results_%d.pt" % model_ind))

fig, axarr = plt.subplots(1, figsize=(4, 1 * 4))
l_MIs = r["diagnostics"]["l_MIs"]
#axarr[0].plot(r["diagnostics"]["l_MIs"])
sns.lineplot(x=range(len(l_MIs)), y=l_MIs, palette="deep", ax=axarr)
//  [python]
times = ['Training (minutes)', 'Predicting (seconds)']
titles = ['Training', 'Predicting']
color = ['orange', 'blue']

plot_no = 1


for idx, title in enumerate(titles):
    # sns.boxplot(data=df_min_cag, x='Nodes', y=y)
    # plt.title(f'Training Times')
    # plt.savefig(f'{out_dir}{plot_no}_{y} - box.png')
    # plt.close()
    # plot_no += 1
    #
    # sns.violinplot(data=df_min_cag, x='Nodes', y=y, scale='count', bw=.15, inner='box')
    # plt.title(f'Training Times')
    # plt.savefig(f'{out_dir}{plot_no}_{y} - violin.png')
    # plt.close()
    # plot_no += 1

    plt.plot(df_min_cag['Nodes'], df_min_cag[times[idx]], marker='o', color=color[idx], linewidth=2)
    plt.title(title + ' Times Against Number of Nodes ($n$)\nfor CAGs with the minimum number of edges ($n - 1$)')
    plt.tight_layout()
    plt.savefig(f'{out_dir}{plot_no}_{title} - line.png')
    # plt.show()
    plt.close()
    plot_no += 1
//  [python]
times = ['Training (minutes)', 'Predicting (seconds)']
titles = ['Training', 'Predicting']
color = ['orange', 'blue']

plot_no = 1


for idx, title in enumerate(titles):
    # sns.boxplot(data=df_min_cag, x='Nodes', y=y)
    # plt.title(f'Training Times')
    # plt.savefig(f'{out_dir}{plot_no}_{y} - box.png')
    # plt.close()
    # plot_no += 1
    #
    # sns.violinplot(data=df_min_cag, x='Nodes', y=y, scale='count', bw=.15, inner='box')
    # plt.title(f'Training Times')
    # plt.savefig(f'{out_dir}{plot_no}_{y} - violin.png')
    # plt.close()
    # plot_no += 1

    sns.lineplot(data=df_min_cag, x='Nodes', y=times[idx], marker='o', color=color[idx], linewidth=2)
    plt.title(title + ' Times Against Number of Nodes ($n$)\nfor CAGs with the minimum number of edges ($n - 1$)')
    plt.tight_layout()
    plt.savefig(f'{out_dir}{plot_no}_{title} - line.png')
    # plt.show()
    plt.close()
    plot_no += 1
//  [python]
def plot(self) -> None:
        """Plots Principal Component (PC) changes during the embedding search.

        Args:
            pc_change (list): List of fractional changes in the target PC
                during the search as dimensions are progressively added.
            other_pc_change (list): List of the sum of fractional changes in
                all other PCs during the search as dimensions are added.
            title (str, optional): Title for plot. Defaults to None.
        """
        import matplotlib.pyplot as plt
        import seaborn as sns

        x = range(len(self.pc_change))
        plt.clf()
        sns.plt.plot(x, self.pc_change, color='r', label='Target PC % Change')
        sns.plt.plot(x, self.other_pc_change, color='b', label='Other PC % Change')
        sns.plt.plot(x, self.preds, color='green', label='End prediction')
        plt.axhline(y=0, color='black', linestyle='--')
        plt.axhline(y=1, color='gray', linestyle='--')
        plt.xlabel('Search depth (dimensions)')
//  [python]
def plot(self) -> None:
        """Plots Principal Component (PC) changes during the embedding search.

        Args:
            pc_change (list): List of fractional changes in the target PC
                during the search as dimensions are progressively added.
            other_pc_change (list): List of the sum of fractional changes in
                all other PCs during the search as dimensions are added.
            title (str, optional): Title for plot. Defaults to None.
        """
        import matplotlib.pyplot as plt
        import seaborn as sns

        x = range(len(self.pc_change))
        plt.clf()
        sns.lineplot(x=x, y=self.pc_change, color='r', label='Target PC % Change')
        sns.lineplot(x=x, y=self.other_pc_change, color='b', label='Other PC % Change')
        sns.lineplot(x=x, y=self.preds, color='green', label='End prediction')
        plt.axhline(y=0, color='black', linestyle='--')
        plt.axhline(y=1, color='gray', linestyle='--')
        plt.xlabel('Search depth (dimensions)')
//  [python]
def plot_subset(experiments, suffix, unique_models, model_colors, full_data, OUTPUT_DIR):
    print("in the plot subset function")
    # Increase the vertical space if needed
    fig, axes = plt.subplots(len(experiments), len(unique_models), figsize=(20, 6 * len(experiments)), sharex=True, sharey=True)

    if len(experiments) == 1:
        axes = [axes]  # Wrap it in a list to make the indexing below work
    elif len(unique_models) == 1:
        axes = axes.reshape(-1, 1)  # If only one model, ensure axes are 2D array

    for i, experiment in enumerate(experiments):
        for j, model in enumerate(unique_models):
            ax = axes[i][j] if axes.ndim > 1 else axes[i]
            df_filtered = full_data[(full_data['experiment'] == experiment) & (full_data['model'] == model)]
            line = sns.tsplot(ax=ax, time='day', value='total', data=df_filtered, color=model_colors[model], label=f"{model} - {experiment}")
            
            df_average = df_filtered.groupby('day')['total'].mean().reset_index()
            sns.scatterplot(ax=ax, x='day', y='total', data=df_average, color=model_colors[model], s=50, zorder=10)

            ax.set_ylabel("Escalation Score", fontsize=16)
            ax.grid(True)
            ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True, nbins=6))
            ax.set_xlabel("Time t [Days]", fontsize=14)

            # Reduce the font size if the legend is still too large
            ax.legend(loc='upper left', fontsize=15)

    plt.suptitle(f"Escalation Scores Over Time by Model and Experiment ({suffix})", fontsize=28)
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])
    output_filepath = os.path.join(OUTPUT_DIR, f"escalation_scores_plot_{suffix}.pdf")
    plt.savefig(output_filepath, bbox_inches='tight')  # Save with tight bounding box to include legend
    plt.show()
//  [python]
def plot_subset(experiments, suffix, unique_models, model_colors, full_data, OUTPUT_DIR):
    print("in the plot subset function")
    # Increase the vertical space if needed
    fig, axes = plt.subplots(len(experiments), len(unique_models), figsize=(20, 6 * len(experiments)), sharex=True, sharey=True)

    if len(experiments) == 1:
        axes = [axes]  # Wrap it in a list to make the indexing below work
    elif len(unique_models) == 1:
        axes = axes.reshape(-1, 1)  # If only one model, ensure axes are 2D array

    for i, experiment in enumerate(experiments):
        for j, model in enumerate(unique_models):
            ax = axes[i][j] if axes.ndim > 1 else axes[i]
            df_filtered = full_data[(full_data['experiment'] == experiment) & (full_data['model'] == model)]
            line = sns.lineplot(ax=ax, x='day', y='total', data=df_filtered, color=model_colors[model], label=f"{model} - {experiment}")
            
            df_average = df_filtered.groupby('day')['total'].mean().reset_index()
            sns.scatterplot(ax=ax, x='day', y='total', data=df_average, color=model_colors[model], s=50, zorder=10)

            ax.set_ylabel("Escalation Score", fontsize=16)
            ax.grid(True)
            ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True, nbins=6))
            ax.set_xlabel("Time t [Days]", fontsize=14)

            # Reduce the font size if the legend is still too large
            ax.legend(loc='upper left', fontsize=15)

    plt.suptitle(f"Escalation Scores Over Time by Model and Experiment ({suffix})", fontsize=28)
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])
    output_filepath = os.path.join(OUTPUT_DIR, f"escalation_scores_plot_{suffix}.pdf")
    plt.savefig(output_filepath, bbox_inches='tight')  # Save with tight bounding box to include legend
    plt.show()
//  [python]
def plotCdf(self):
        """Plot the CDF"""
        floatCdf = self.get_float_cdf_or_error()
        seaborn.lineplot(floatCdf["xs"], floatCdf["ys"])
//  [python]
def plot_data(data, x_axis='num episodes', y_axis="average reward", hue="algorithm", smooth=1, ax=None, **kwargs):
    if smooth > 1:
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[y_axis])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x, y, 'same') / np.convolve(z, y, 'same')
            datum[y_axis] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True, sort=True)

    sns.tsplot(data=data, time=x_axis, value=y_axis,
                 unit="run", condition=hue, ci='sd', ax=ax, **kwargs)
    # ax.legend(loc='best').set_draggable(True)
    """Spining up style"""

    ax.legend(loc='upper center', ncol=9, handlelength=1, frameon=False,
              mode="expand", borderaxespad=0.02, prop={'size': 8})

    xscale = np.max(np.asarray(data[x_axis])) > 5e3
    if xscale:
        # Just some formatting niceness: x-axis scale in scientific notation if max x is large
        ax.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.tight_layout(pad=1.2)
//  [python]
def plot_data(data, x_axis='num episodes', y_axis="average reward", hue="algorithm", smooth=1, ax=None, **kwargs):
    if smooth > 1:
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[y_axis])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x, y, 'same') / np.convolve(z, y, 'same')
            datum[y_axis] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True, sort=True)

    sns.lineplot(data=data, x=x_axis, y=y_axis,
                 hue=hue, ci='sd', ax=ax, **kwargs)
    # ax.legend(loc='best').set_draggable(True)
    """Spining up style"""

    ax.legend(loc='upper center', ncol=9, handlelength=1, frameon=False,
              mode="expand", borderaxespad=0.02, prop={'size': 8})

    xscale = np.max(np.asarray(data[x_axis])) > 5e3
    if xscale:
        # Just some formatting niceness: x-axis scale in scientific notation if max x is large
        ax.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.tight_layout(pad=1.2)
//  [python]
def plot_data(data, xaxis="Epoch", value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
	if smooth > 1:
		"""
		smooth data with moving window average.
		that is,
			smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
		where the "smooth" param is width of that window (2k+1)
		"""
		y = np.ones(smooth)
		for datum in data:
			x = np.asarray(datum[value])
			z = np.ones(len(x))
			smoothed_x = np.convolve(x, y, "same") / np.convolve(z, y, "same")
			datum[value] = smoothed_x

	if isinstance(data, list):
		data = pd.concat(data, ignore_index=True)

	# Default
	sns.set(style="whitegrid", font_scale=1.5)
	ax = sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci="sd", **kwargs)
	# ax = sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)
	
	ax.set_xlabel("Steps")
	"""
	If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
	tsplot to lineplot replacing L34 with:

		sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)

	Changes the colorscheme and the default legend style, though.
	"""
	plt.legend(loc="best").set_draggable(True)
	plt.tick_params(direction="out", length=4)
	"""
	For the version of the legend used in the Spinning Up benchmarking page, 
	swap L38 with:

	plt.legend(loc="upper center", ncol=6, handlelength=1,
			   mode="expand", borderaxespad=0., prop={"size": 13})
	"""

	xscale = np.max(np.asarray(data[xaxis])) > 5e3
	if xscale:
		# Just some formatting niceness: x-axis scale in scientific notation if max x is large
		plt.ticklabel_format(style="sci", axis='x', scilimits=(0, 0))

	plt.tight_layout(pad=0.5)
//  [python]
def plot_data(data, xaxis="Epoch", value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
	if smooth > 1:
		"""
		smooth data with moving window average.
		that is,
			smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
		where the "smooth" param is width of that window (2k+1)
		"""
		y = np.ones(smooth)
		for datum in data:
			x = np.asarray(datum[value])
			z = np.ones(len(x))
			smoothed_x = np.convolve(x, y, "same") / np.convolve(z, y, "same")
			datum[value] = smoothed_x

	if isinstance(data, list):
		data = pd.concat(data, ignore_index=True)

	# Default
	sns.set(style="whitegrid", font_scale=1.5)
	# ax = sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci="sd", **kwargs)
	ax = sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)
	
	ax.set_xlabel("Steps")
	"""
	If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
	tsplot to lineplot replacing L34 with:

		sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)

	Changes the colorscheme and the default legend style, though.
	"""
	plt.legend(loc="best").set_draggable(True)
	plt.tick_params(direction="out", length=4)
	"""
	For the version of the legend used in the Spinning Up benchmarking page, 
	swap L38 with:

	plt.legend(loc="upper center", ncol=6, handlelength=1,
			   mode="expand", borderaxespad=0., prop={"size": 13})
	"""

	xscale = np.max(np.asarray(data[xaxis])) > 5e3
	if xscale:
		# Just some formatting niceness: x-axis scale in scientific notation if max x is large
		plt.ticklabel_format(style="sci", axis='x', scilimits=(0, 0))

	plt.tight_layout(pad=0.5)
//  [python]
def draw_plot():
    # ax1
    ax1 = pw.Brick(figsize=(3, 2))  # 每个子图调用pw.Brick方法
    fmri = sns.load_dataset("fmri") # 加载数据集，需要能够访问github

    sns.tsplot(x="timepoint", y="signal", hue="region", style="event", data=fmri, ax=ax1)
    ax1.move_legend(new_loc='upper left', bbox_to_anchor=(1.05, 1.0))
    ax1.set_title("ax1")

    # ax2
    ax2 = pw.Brick(figsize=(1, 2))
    titanic = sns.load_dataset("titanic")
    sns.barplot(x="sex", y="survived", hue="class", data=titanic, ax=ax2)
    ax2.move_legend(new_loc='upper left', bbox_to_anchor=(1.05, 1.0))
    ax2.set_title("ax2")

    # ax3
    ax3 = pw.Brick(figsize=(5, 2))
    diamonds = sns.load_dataset("diamonds")
    sns.histplot(diamonds, x="price", hue="cut", multiple="stack", palette="light:m_r", edgecolor=".3", linewidth=.5,
                 log_scale=True, ax=ax3)
    ax3.move_legend(new_loc='upper left', bbox_to_anchor=(1.0, 1.0))
    ax3.set_title("ax3")

    # ax4
    ax4 = pw.Brick(figsize=(6, 2))
    tips = sns.load_dataset("tips")
    sns.violinplot(data=tips, x="day", y="total_bill", hue="smoker", split=True, inner="quart", linewidth=1,
                   palette={"Yes": "b", "No": ".85"}, ax=ax4)
    ax4.move_legend("upper left", bbox_to_anchor=(1.02, 1.0))
    ax4.set_title("ax4")

    # ax5
    ax5 = pw.Brick(figsize=(5, 2))
    rs = np.random.RandomState(365)
    values = rs.randn(365, 4).cumsum(axis=0)
    dates = pd.date_range("1 1 2016", periods=365, freq="D")
    data = pd.DataFrame(values, dates, columns=["A", "B", "C", "D"])
    data = data.rolling(7).mean()
    sns.tsplot(data=data, palette="tab10", linewidth=2.5, ax=ax5)
    ax5.set_xlabel("date")
    ax5.set_ylabel("value")
    ax5.move_legend("upper left", bbox_to_anchor=(1.02, 1.0))
    ax5.set_title("ax5")

    # 拼图
    ax12345 = (ax1 | ax2) / (ax3 / ax4) / (ax5)
    ax12345.savefig("./pics/ax12345.png")
//  [python]
def draw_plot():
    # ax1
    ax1 = pw.Brick(figsize=(3, 2))  # 每个子图调用pw.Brick方法
    fmri = sns.load_dataset("fmri") # 加载数据集，需要能够访问github

    sns.lineplot(x="timepoint", y="signal", hue="region", style="event", data=fmri, ax=ax1)
    ax1.move_legend(new_loc='upper left', bbox_to_anchor=(1.05, 1.0))
    ax1.set_title("ax1")

    # ax2
    ax2 = pw.Brick(figsize=(1, 2))
    titanic = sns.load_dataset("titanic")
    sns.barplot(x="sex", y="survived", hue="class", data=titanic, ax=ax2)
    ax2.move_legend(new_loc='upper left', bbox_to_anchor=(1.05, 1.0))
    ax2.set_title("ax2")

    # ax3
    ax3 = pw.Brick(figsize=(5, 2))
    diamonds = sns.load_dataset("diamonds")
    sns.histplot(diamonds, x="price", hue="cut", multiple="stack", palette="light:m_r", edgecolor=".3", linewidth=.5,
                 log_scale=True, ax=ax3)
    ax3.move_legend(new_loc='upper left', bbox_to_anchor=(1.0, 1.0))
    ax3.set_title("ax3")

    # ax4
    ax4 = pw.Brick(figsize=(6, 2))
    tips = sns.load_dataset("tips")
    sns.violinplot(data=tips, x="day", y="total_bill", hue="smoker", split=True, inner="quart", linewidth=1,
                   palette={"Yes": "b", "No": ".85"}, ax=ax4)
    ax4.move_legend("upper left", bbox_to_anchor=(1.02, 1.0))
    ax4.set_title("ax4")

    # ax5
    ax5 = pw.Brick(figsize=(5, 2))
    rs = np.random.RandomState(365)
    values = rs.randn(365, 4).cumsum(axis=0)
    dates = pd.date_range("1 1 2016", periods=365, freq="D")
    data = pd.DataFrame(values, dates, columns=["A", "B", "C", "D"])
    data = data.rolling(7).mean()
    sns.lineplot(data=data, palette="tab10", linewidth=2.5, ax=ax5)
    ax5.set_xlabel("date")
    ax5.set_ylabel("value")
    ax5.move_legend("upper left", bbox_to_anchor=(1.02, 1.0))
    ax5.set_title("ax5")

    # 拼图
    ax12345 = (ax1 | ax2) / (ax3 / ax4) / (ax5)
    ax12345.savefig("./pics/ax12345.png")
//  [python]
def produce_plots(data, prefix, max_seconds, max_steps):
    data_solved = [(dp.depth, int(dp.is_solved)) for dp in data]
    data_steps = [(dp.depth, dp.solve_steps) for dp in data if dp.is_solved]

    if max_steps is not None:
        suffix = "(steps limit %d)" % max_steps
    else:
        suffix = "(time limit %d secs)" % max_seconds

    sns.set()
    d, v = zip(*data_solved)
    plot = sns.plt.plot(d, v)
    sns.plt.title("Solve ratio per depth %s" % suffix)
    sns.plt.savefig(prefix + "-solve_vs_depth.png")

    sns.plt.clf()
    d, v = zip(*data_steps)
    plot = sns.plt.plot(d, v)
    sns.plt.title("Steps to solve per depth %s" % suffix)
    sns.plt.savefig(prefix + "-steps_vs_depth.png")
//  [python]
def produce_plots(data, prefix, max_seconds, max_steps):
    data_solved = [(dp.depth, int(dp.is_solved)) for dp in data]
    data_steps = [(dp.depth, dp.solve_steps) for dp in data if dp.is_solved]

    if max_steps is not None:
        suffix = "(steps limit %d)" % max_steps
    else:
        suffix = "(time limit %d secs)" % max_seconds

    sns.set()
    d, v = zip(*data_solved)
    plot = sns.lineplot(d, v)
    plot.set_title("Solve ratio per depth %s" % suffix)
    plot.get_figure().savefig(prefix + "-solve_vs_depth.png")

    plt.clf()
    d, v = zip(*data_steps)
    plot = sns.lineplot(d, v)
    plot.set_title("Steps to solve per depth %s" % suffix)
    plot.get_figure().savefig(prefix + "-steps_vs_depth.png")
//  [python]
explained_var_ratio = pca_model.eigenvals / pca_model.eigenvals.sum()

X_df_ = pca_model.project(num_of_PCs)

fig, axes = plt.subplots(2,4,figsize=(8,4))
axes = axes.flatten()

for col_idx, ax_idx in zip(list(X_df_.columns),axes):
    plt.plot(X_df_[col_idx],ax = ax_idx)
    plt.plot(X_df[col_idx],ax = ax_idx) 
    plt.plot(X_df[col_idx] - X_df_[col_idx], c = 'k', ax = ax_idx) 
    ax_idx.set_xticks([])
    ax_idx.set_yticks([])
    ax_idx.axhline(y = 0, c = 'k')
//  [python]
explained_var_ratio = pca_model.eigenvals / pca_model.eigenvals.sum()

X_df_ = pca_model.project(num_of_PCs)

fig, axes = plt.subplots(2,4,figsize=(8,4))
axes = axes.flatten()

for col_idx, ax_idx in zip(list(X_df_.columns),axes):
    sns.lineplot(X_df_[col_idx],ax = ax_idx)
    sns.lineplot(X_df[col_idx],ax = ax_idx) 
    sns.lineplot(X_df[col_idx] - X_df_[col_idx], c = 'k', ax = ax_idx) 
    ax_idx.set_xticks([])
    ax_idx.set_yticks([])
    ax_idx.axhline(y = 0, c = 'k')
//  [python]
def make_lineplot(data, fname=None, line_kwargs=None, **kwargs):
    """
    Generates lineplot of number of significant correlations for null methods

    Parameters
    ----------
    data : pandas.DataFrame
        Dataframe with at least columns ['scale', 'n-sig', 'spintype'] for
        plotting
    fname : str or os.PathLike, optional
        Path to where generated figure should be saved
    kwargs : key-value pairs
        Passed to `ax.set()`

    Returns
    -------
    fig : matplotlib.figure.Figure
        Plotted figure
    """

    lp_kwargs = dict(ci=None, estimator=None, linewidth=3, legend=False)
    if line_kwargs is not None:
        lp_kwargs.update(line_kwargs)
    ax_kwargs = dict(xticklabels=[], xlabel='resolution',
                     ylabel='significant correlations remaining')
    ax_kwargs.update(kwargs)

    # make plot of number of significant correlations remaining after
    # corection across resolutions of the given
    fig, ax1 = plt.subplots(1, 1)
    ax1 = sns.tsplot(x='scale', y='n_sig', hue='spintype', ax=ax1,
                       data=data, **lp_kwargs)
    ax1.set(xticks=np.asarray(ax1.get_xticks()), **ax_kwargs)
    sns.despine(ax=ax1)

    if fname is not None:
        fig.savefig(fname, bbox_inches='tight', transparent=True)
        plt.close(fig=fig)

    return fig
//  [python]
def make_lineplot(data, fname=None, line_kwargs=None, **kwargs):
    """
    Generates lineplot of number of significant correlations for null methods

    Parameters
    ----------
    data : pandas.DataFrame
        Dataframe with at least columns ['scale', 'n-sig', 'spintype'] for
        plotting
    fname : str or os.PathLike, optional
        Path to where generated figure should be saved
    kwargs : key-value pairs
        Passed to `ax.set()`

    Returns
    -------
    fig : matplotlib.figure.Figure
        Plotted figure
    """

    lp_kwargs = dict(ci=None, estimator=None, linewidth=3, legend=False)
    if line_kwargs is not None:
        lp_kwargs.update(line_kwargs)
    ax_kwargs = dict(xticklabels=[], xlabel='resolution',
                     ylabel='significant correlations remaining')
    ax_kwargs.update(kwargs)

    # make plot of number of significant correlations remaining after
    # corection across resolutions of the given
    fig, ax1 = plt.subplots(1, 1)
    ax1 = sns.lineplot(x='scale', y='n_sig', hue='spintype', ax=ax1,
                       data=data, **lp_kwargs)
    ax1.set(xticks=np.asarray(ax1.get_xticks()), **ax_kwargs)
    sns.despine(ax=ax1)

    if fname is not None:
        fig.savefig(fname, bbox_inches='tight', transparent=True)
        plt.close(fig=fig)

    return fig
//  [python]
def plot_sns_figure(self, metrics, df_metrics, title_end, text_legend, use_log_scale=True, save_fig=True):

        self.fig, ax = plt.subplots()
        # self.fig.set_size_inches(9, 6)
        self.fig.set_size_inches(8, 6)
        title_text = 'Impact of K in {}'.format(metrics)

        # ax.set_title(title_text)
        ax.set_xlabel('# robots')

        if metrics == "rate_ReachGoal":
            label_text_y = "Success Rate"
            ax.set_ylabel(r'$\alpha$')
        elif metrics == "mean_deltaFT":
            label_text_y = "Flowtime Increase"
            ax.set_ylabel(r'$\delta_{FT}$')

        self.label_data_text_combine = []

        # custom_cycler = (cycler(color=['b', 'g', 'r', 'm']) +
        #                  cycler(linestyle=['-', '--', ':', '-.']))


        ## GNN with OE
        # custom_cycler = (cycler(color=['k', 'brown', 'blue', 'orange', 'green', 'red',  'cyan']))
        list_color = ['k', 'brown', 'blue', 'orange', 'green', 'red',  'cyan']

        # ax.set_prop_cycle(custom_cycler)
        # sns.palplot(sns.color_palette("Paired"))
        with plt.rc_context({'lines.linewidth':3}):
            for i, group in df_metrics.groupby('Exp setup'):
                ax.plot(group['# robots'], group[label_text_y], marker='o', label=i)


        if use_log_scale:
            ax.set_yscale('log')
        plt.grid()


        if metrics == "rate_ReachGoal":
            ax.legend(loc='lower left',ncol=1, borderaxespad=0.1,handleheight=0.1, columnspacing=0.2, labelspacing=0.05)
            start, end = ax.get_ylim()
            ax.set_ylim([0, 1])
        elif metrics == "mean_deltaFT":
            # ## GNN
            ax.legend(loc='upper left', ncol=1, borderaxespad=0.1,handleheight=0.1, columnspacing=0.2, labelspacing=0.05)
            start, end = ax.get_ylim()
            # ax.set_ylim([start, end*3])
            # ax.set_ylim([0.02, 3])


        # ax.legend()

        self.show()
        if save_fig:
            self.save_fig("{}_{}".format(metrics,title_end))
//  [python]
def plot_sns_figure(self, metrics, df_metrics, title_end, text_legend, use_log_scale=True, save_fig=True):

        self.fig, ax = plt.subplots()
        # self.fig.set_size_inches(9, 6)
        self.fig.set_size_inches(8, 6)
        title_text = 'Impact of K in {}'.format(metrics)

        # ax.set_title(title_text)
        ax.set_xlabel('# robots')

        if metrics == "rate_ReachGoal":
            label_text_y = "Success Rate"
            ax.set_ylabel(r'$\alpha$')
        elif metrics == "mean_deltaFT":
            label_text_y = "Flowtime Increase"
            ax.set_ylabel(r'$\delta_{FT}$')

        self.label_data_text_combine = []

        # custom_cycler = (cycler(color=['b', 'g', 'r', 'm']) +
        #                  cycler(linestyle=['-', '--', ':', '-.']))


        ## GNN with OE
        # custom_cycler = (cycler(color=['k', 'brown', 'blue', 'orange', 'green', 'red',  'cyan']))
        list_color = ['k', 'brown', 'blue', 'orange', 'green', 'red',  'cyan']

        # ax.set_prop_cycle(custom_cycler)
        # sns.palplot(sns.color_palette("Paired"))
        with plt.rc_context({'lines.linewidth':3}):
            ax = sns.lineplot(x='# robots', y=label_text_y,data=df_metrics,hue='Exp setup',style='Exp setup', markers=True)


        if use_log_scale:
            ax.set_yscale('log')
        plt.grid()


        if metrics == "rate_ReachGoal":
            ax.legend(loc='lower left',ncol=1, borderaxespad=0.1,handleheight=0.1, columnspacing=0.2, labelspacing=0.05)
            start, end = ax.get_ylim()
            ax.set_ylim([0, 1])
        elif metrics == "mean_deltaFT":
            # ## GNN
            ax.legend(loc='upper left', ncol=1, borderaxespad=0.1,handleheight=0.1, columnspacing=0.2, labelspacing=0.05)
            start, end = ax.get_ylim()
            # ax.set_ylim([start, end*3])
            # ax.set_ylim([0.02, 3])


        # ax.legend()

        self.show()
        if save_fig:
            self.save_fig("{}_{}".format(metrics,title_end))