Python matplotlib.pyplot.close() Examples
The following are 30
code examples of matplotlib.pyplot.close().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.

Example #1
Source File: plotFigures.py From fullrmc with GNU Affero General Public License v3.0 | 7 votes |
def plot(PDF, figName, imgpath, show=False, save=True): # plot output = PDF.get_constraint_value() plt.plot(PDF.experimentalDistances,PDF.experimentalPDF, 'ro', label="experimental", markersize=7.5, markevery=1 ) plt.plot(PDF.shellsCenter, output["pdf"], 'k', linewidth=3.0, markevery=25, label="total" ) styleIndex = 0 for key in output: val = output[key] if key in ("pdf_total", "pdf"): continue elif "inter" in key: plt.plot(PDF.shellsCenter, val, STYLE[styleIndex], markevery=5, label=key.split('rdf_inter_')[1] ) styleIndex+=1 plt.legend(frameon=False, ncol=1) # set labels plt.title("$\\chi^{2}=%.6f$"%PDF.squaredDeviations, size=20) plt.xlabel("$r (\AA)$", size=20) plt.ylabel("$g(r)$", size=20) # show plot if save: plt.savefig(figName) if show: plt.show() plt.close()
Example #2
Source File: tests_emg.py From NeuroKit with MIT License | 7 votes |
def test_emg_plot(): sampling_rate = 1000 emg = nk.emg_simulate(duration=10, sampling_rate=1000, burst_number=3) emg_summary, _ = nk.emg_process(emg, sampling_rate=sampling_rate) # Plot data over samples. nk.emg_plot(emg_summary) # This will identify the latest figure. fig = plt.gcf() assert len(fig.axes) == 2 titles = ["Raw and Cleaned Signal", "Muscle Activation"] for (ax, title) in zip(fig.get_axes(), titles): assert ax.get_title() == title assert fig.get_axes()[1].get_xlabel() == "Samples" np.testing.assert_array_equal(fig.axes[0].get_xticks(), fig.axes[1].get_xticks()) plt.close(fig) # Plot data over time. nk.emg_plot(emg_summary, sampling_rate=sampling_rate) # This will identify the latest figure. fig = plt.gcf() assert fig.get_axes()[1].get_xlabel() == "Time (seconds)"
Example #3
Source File: timeplots.py From NanoPlot with GNU General Public License v3.0 | 7 votes |
def quality_over_time(dfs, path, figformat, title, plot_settings={}): time_qual = Plot(path=path + "TimeQualityViolinPlot." + figformat, title="Violin plot of quality over time") sns.set(style="white", **plot_settings) ax = sns.violinplot(x="timebin", y="quals", data=dfs, inner=None, cut=0, linewidth=0) ax.set(xlabel='Interval (hours)', ylabel="Basecall quality", title=title or time_qual.title) plt.xticks(rotation=45, ha='center', fontsize=8) time_qual.fig = ax.get_figure() time_qual.save(format=figformat) plt.close("all") return time_qual
Example #4
Source File: timeplots.py From NanoPlot with GNU General Public License v3.0 | 7 votes |
def sequencing_speed_over_time(dfs, path, figformat, title, plot_settings={}): time_duration = Plot(path=path + "TimeSequencingSpeed_ViolinPlot." + figformat, title="Violin plot of sequencing speed over time") sns.set(style="white", **plot_settings) if "timebin" not in dfs: dfs['timebin'] = add_time_bins(dfs) mask = dfs['duration'] != 0 ax = sns.violinplot(x=dfs.loc[mask, "timebin"], y=dfs.loc[mask, "lengths"] / dfs.loc[mask, "duration"], inner=None, cut=0, linewidth=0) ax.set(xlabel='Interval (hours)', ylabel="Sequencing speed (nucleotides/second)", title=title or time_duration.title) plt.xticks(rotation=45, ha='center', fontsize=8) time_duration.fig = ax.get_figure() time_duration.save(format=figformat) plt.close("all") return time_duration
Example #5
Source File: display_methods.py From indras_net with GNU General Public License v3.0 | 6 votes |
def __init__(self, title, varieties, data_points, attrs, anim=False, data_func=None, is_headless=False): global anim_func plt.close() self.legend = ["Type"] self.title = title # self.anim = anim # self.data_func = data_func for i in varieties: data_points = len(varieties[i]["data"]) break self.headless = is_headless self.draw_graph(data_points, varieties, attrs) # if anim and not self.headless: # anim_func = animation.FuncAnimation(self.fig, # self.update_plot, # frames=1000, # interval=500, # blit=False)
Example #6
Source File: utils.py From dc_tts with Apache License 2.0 | 6 votes |
def plot_alignment(alignment, gs, dir=hp.logdir): """Plots the alignment. Args: alignment: A numpy array with shape of (encoder_steps, decoder_steps) gs: (int) global step. dir: Output path. """ if not os.path.exists(dir): os.mkdir(dir) fig, ax = plt.subplots() im = ax.imshow(alignment) fig.colorbar(im) plt.title('{} Steps'.format(gs)) plt.savefig('{}/alignment_{}.png'.format(dir, gs), format='png') plt.close(fig)
Example #7
Source File: nav_utils.py From DOTA_models with Apache License 2.0 | 6 votes |
def save_d_at_t(outputs, global_step, output_dir, metric_summary, N): """Save distance to goal at all time steps. Args: outputs : [gt_dist_to_goal]. global_step : number of iterations. output_dir : output directory. metric_summary : to append scalars to summary. N : number of outputs to process. """ d_at_t = np.concatenate(map(lambda x: x[0][:,:,0]*1, outputs), axis=0) fig, axes = utils.subplot(plt, (1,1), (5,5)) axes.plot(np.arange(d_at_t.shape[1]), np.mean(d_at_t, axis=0), 'r.') axes.set_xlabel('time step') axes.set_ylabel('dist to next goal') axes.grid('on') file_name = os.path.join(output_dir, 'dist_at_t_{:d}.png'.format(global_step)) with fu.fopen(file_name, 'w') as f: fig.savefig(f, bbox_inches='tight', transparent=True, pad_inches=0) file_name = os.path.join(output_dir, 'dist_at_t_{:d}.pkl'.format(global_step)) utils.save_variables(file_name, [d_at_t], ['d_at_t'], overwrite=True) plt.close(fig) return None
Example #8
Source File: utils.py From pruning_yolov3 with GNU General Public License v3.0 | 6 votes |
def plot_images(imgs, targets, paths=None, fname='images.jpg'): # Plots training images overlaid with targets imgs = imgs.cpu().numpy() targets = targets.cpu().numpy() # targets = targets[targets[:, 1] == 21] # plot only one class fig = plt.figure(figsize=(10, 10)) bs, _, h, w = imgs.shape # batch size, _, height, width bs = min(bs, 16) # limit plot to 16 images ns = np.ceil(bs ** 0.5) # number of subplots for i in range(bs): boxes = xywh2xyxy(targets[targets[:, 0] == i, 2:6]).T boxes[[0, 2]] *= w boxes[[1, 3]] *= h plt.subplot(ns, ns, i + 1).imshow(imgs[i].transpose(1, 2, 0)) plt.plot(boxes[[0, 2, 2, 0, 0]], boxes[[1, 1, 3, 3, 1]], '.-') plt.axis('off') if paths is not None: s = Path(paths[i]).name plt.title(s[:min(len(s), 40)], fontdict={'size': 8}) # limit to 40 characters fig.tight_layout() fig.savefig(fname, dpi=200) plt.close()
Example #9
Source File: massachusetts_road_segm.py From Recipes with MIT License | 6 votes |
def plot_some_results(pred_fn, test_generator, n_images=10): fig_ctr = 0 for data, seg in test_generator: res = pred_fn(data) for d, s, r in zip(data, seg, res): plt.figure(figsize=(12, 6)) plt.subplot(1, 3, 1) plt.imshow(d.transpose(1,2,0)) plt.title("input patch") plt.subplot(1, 3, 2) plt.imshow(s[0]) plt.title("ground truth") plt.subplot(1, 3, 3) plt.imshow(r) plt.title("segmentation") plt.savefig("road_segmentation_result_%03.0f.png"%fig_ctr) plt.close() fig_ctr += 1 if fig_ctr > n_images: break
Example #10
Source File: malware.py From trees with Apache License 2.0 | 6 votes |
def classify(self, features, show=False): recs, _ = features.shape result_shape = (features.shape[0], len(self.root)) scores = np.zeros(result_shape) print scores.shape R = Record(np.arange(recs, dtype=int), features) for i, T in enumerate(self.root): for idxs, result in classify(T, R): for idx in idxs.indexes(): scores[idx, i] = float(result[0]) / sum(result.values()) if show: plt.cla() plt.clf() plt.close() plt.imshow(scores, cmap=plt.cm.gray) plt.title('Scores matrix') plt.savefig(r"../scratch/tree_scores.png", bbox_inches='tight') return scores
Example #11
Source File: data_provider.py From ICDAR-2019-SROIE with MIT License | 6 votes |
def generator(vis=False): image_list = np.array(get_training_data()) print('{} training images in {}'.format(image_list.shape[0], DATA_FOLDER)) index = np.arange(0, image_list.shape[0]) while True: np.random.shuffle(index) for i in index: try: im_fn = image_list[i] im = cv2.imread(im_fn) h, w, c = im.shape im_info = np.array([h, w, c]).reshape([1, 3]) _, fn = os.path.split(im_fn) fn, _ = os.path.splitext(fn) txt_fn = os.path.join(DATA_FOLDER, "label", fn + '.txt') if not os.path.exists(txt_fn): print("Ground truth for image {} not exist!".format(im_fn)) continue bbox = load_annoataion(txt_fn) if len(bbox) == 0: print("Ground truth for image {} empty!".format(im_fn)) continue if vis: for p in bbox: cv2.rectangle(im, (p[0], p[1]), (p[2], p[3]), color=(0, 0, 255), thickness=1) fig, axs = plt.subplots(1, 1, figsize=(30, 30)) axs.imshow(im[:, :, ::-1]) axs.set_xticks([]) axs.set_yticks([]) plt.tight_layout() plt.show() plt.close() yield [im], bbox, im_info except Exception as e: print(e) continue
Example #12
Source File: callback_video.py From pymoo with Apache License 2.0 | 6 votes |
def notify(self, algorithm, **kwargs): if algorithm.n_gen == 1 or algorithm.n_gen % self.nth_gen == 0: try: ret = self.do(algorithm.problem, algorithm, **kwargs) if self.do_show: plt.show() if self.video is not None: self.video.record() if self.do_close: plt.close() return ret except Exception as ex: if self.exception_if_not_applicable: raise ex
Example #13
Source File: matplotlib_trading_chart.py From tensortrade with Apache License 2.0 | 6 votes |
def _render_price(self, step_range, times, current_step): self.price_ax.clear() # Plot price using candlestick graph from mpl_finance self.price_ax.plot(times, self.df['close'].values[step_range], color="black") last_time = self.df.index.values[current_step] last_close = self.df['close'].values[current_step] last_high = self.df['high'].values[current_step] # Print the current price to the price axis self.price_ax.annotate('{0:.2f}'.format(last_close), (last_time, last_close), xytext=(last_time, last_high), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color="black", fontsize="small") # Shift price axis up to give volume chart space ylim = self.price_ax.get_ylim() self.price_ax.set_ylim(ylim[0] - (ylim[1] - ylim[0]) * VOLUME_CHART_HEIGHT, ylim[1])
Example #14
Source File: matplotlib_trading_chart.py From tensortrade with Apache License 2.0 | 6 votes |
def _render_trades(self, step_range, trades): trades = [trade for sublist in trades.values() for trade in sublist] for trade in trades: if trade.step in range(sys.maxsize)[step_range]: date = self.df.index.values[trade.step] close = self.df['close'].values[trade.step] color = 'green' if trade.side is TradeSide.SELL: color = 'red' self.price_ax.annotate(' ', (date, close), xytext=(date, close), size="large", arrowprops=dict(arrowstyle='simple', facecolor=color))
Example #15
Source File: prod_basis.py From pyscf with Apache License 2.0 | 6 votes |
def generate_png_chess_dp_vertex(self): """Produces pictures of the dominant product vertex a chessboard convention""" import matplotlib.pylab as plt plt.ioff() dab2v = self.get_dp_vertex_doubly_sparse() for i, ab in enumerate(dab2v): fname = "chess-v-{:06d}.png".format(i) print('Matrix No.#{}, Size: {}, Type: {}'.format(i+1, ab.shape, type(ab)), fname) if type(ab) != 'numpy.ndarray': ab = ab.toarray() fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.set_aspect('equal') plt.imshow(ab, interpolation='nearest', cmap=plt.cm.ocean) plt.colorbar() plt.savefig(fname) plt.close(fig)
Example #16
Source File: visualize.py From neat-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_species(statistics, view=False, filename='speciation.svg'): """ Visualizes speciation throughout evolution. """ if plt is None: warnings.warn("This display is not available due to a missing optional dependency (matplotlib)") return species_sizes = statistics.get_species_sizes() num_generations = len(species_sizes) curves = np.array(species_sizes).T fig, ax = plt.subplots() ax.stackplot(range(num_generations), *curves) plt.title("Speciation") plt.ylabel("Size per Species") plt.xlabel("Generations") plt.savefig(filename) if view: plt.show() plt.close()
Example #17
Source File: visualize.py From neat-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_species(statistics, view=False, filename='speciation.svg'): """ Visualizes speciation throughout evolution. """ if plt is None: warnings.warn("This display is not available due to a missing optional dependency (matplotlib)") return species_sizes = statistics.get_species_sizes() num_generations = len(species_sizes) curves = np.array(species_sizes).T fig, ax = plt.subplots() ax.stackplot(range(num_generations), *curves) plt.title("Speciation") plt.ylabel("Size per Species") plt.xlabel("Generations") plt.savefig(filename) if view: plt.show() plt.close()
Example #18
Source File: visualize.py From neat-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_species(statistics, view=False, filename='speciation.svg'): """ Visualizes speciation throughout evolution. """ if plt is None: warnings.warn("This display is not available due to a missing optional dependency (matplotlib)") return species_sizes = statistics.get_species_sizes() num_generations = len(species_sizes) curves = np.array(species_sizes).T fig, ax = plt.subplots() ax.stackplot(range(num_generations), *curves) plt.title("Speciation") plt.ylabel("Size per Species") plt.xlabel("Generations") plt.savefig(filename) if view: plt.show() plt.close()
Example #19
Source File: visualize.py From neat-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_species(statistics, view=False, filename='speciation.svg'): """ Visualizes speciation throughout evolution. """ if plt is None: warnings.warn("This display is not available due to a missing optional dependency (matplotlib)") return species_sizes = statistics.get_species_sizes() num_generations = len(species_sizes) curves = np.array(species_sizes).T fig, ax = plt.subplots() ax.stackplot(range(num_generations), *curves) plt.title("Speciation") plt.ylabel("Size per Species") plt.xlabel("Generations") plt.savefig(filename) if view: plt.show() plt.close()
Example #20
Source File: visualize.py From neat-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_species(statistics, view=False, filename='speciation.svg'): """ Visualizes speciation throughout evolution. """ if plt is None: warnings.warn("This display is not available due to a missing optional dependency (matplotlib)") return species_sizes = statistics.get_species_sizes() num_generations = len(species_sizes) curves = np.array(species_sizes).T fig, ax = plt.subplots() ax.stackplot(range(num_generations), *curves) plt.title("Speciation") plt.ylabel("Size per Species") plt.xlabel("Generations") plt.savefig(filename) if view: plt.show() plt.close()
Example #21
Source File: tests_eog.py From NeuroKit with MIT License | 6 votes |
def test_eog_plot(): eog_signal = nk.data("eog_200hz")["vEOG"] signals, info = nk.eog_process(eog_signal, sampling_rate=200) # Plot nk.eog_plot(signals) fig = plt.gcf() assert len(fig.axes) == 2 titles = ["Raw and Cleaned Signal", "Blink Rate"] legends = [["Raw", "Cleaned", "Blinks"], ["Rate", "Mean"]] ylabels = ["Amplitude (mV)", "Blinks per minute"] for (ax, title, legend, ylabel) in zip(fig.get_axes(), titles, legends, ylabels): assert ax.get_title() == title subplot = ax.get_legend_handles_labels() assert subplot[1] == legend assert ax.get_ylabel() == ylabel assert fig.get_axes()[1].get_xlabel() == "Samples" np.testing.assert_array_equal(fig.axes[0].get_xticks(), fig.axes[1].get_xticks()) plt.close(fig)
Example #22
Source File: tests_eda.py From NeuroKit with MIT License | 6 votes |
def test_eda_plot(): sampling_rate = 1000 eda = nk.eda_simulate(duration=30, sampling_rate=sampling_rate, scr_number=6, noise=0, drift=0.01, random_state=42) eda_summary, _ = nk.eda_process(eda, sampling_rate=sampling_rate) # Plot data over samples. nk.eda_plot(eda_summary) # This will identify the latest figure. fig = plt.gcf() assert len(fig.axes) == 3 titles = ["Raw and Cleaned Signal", "Skin Conductance Response (SCR)", "Skin Conductance Level (SCL)"] for (ax, title) in zip(fig.get_axes(), titles): assert ax.get_title() == title assert fig.get_axes()[2].get_xlabel() == "Samples" np.testing.assert_array_equal(fig.axes[0].get_xticks(), fig.axes[1].get_xticks(), fig.axes[2].get_xticks()) plt.close(fig) # Plot data over seconds. nk.eda_plot(eda_summary, sampling_rate=sampling_rate) # This will identify the latest figure. fig = plt.gcf() assert fig.get_axes()[2].get_xlabel() == "Seconds"
Example #23
Source File: spatial_heatmap.py From NanoPlot with GNU General Public License v3.0 | 6 votes |
def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"): """Taking channel information and creating post run channel activity plots.""" logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads." .format(array.size)) activity_map = Plot( path=path + "." + figformat, title="Number of reads generated per channel") layout = make_layout(maxval=np.amax(array)) valueCounts = pd.value_counts(pd.Series(array)) for entry in valueCounts.keys(): layout.template[np.where(layout.structure == entry)] = valueCounts[entry] plt.figure() ax = sns.heatmap( data=pd.DataFrame(layout.template, index=layout.yticks, columns=layout.xticks), xticklabels="auto", yticklabels="auto", square=True, cbar_kws={"orientation": "horizontal"}, cmap=color, linewidths=0.20) ax.set_title(title or activity_map.title) activity_map.fig = ax.get_figure() activity_map.save(format=figformat) plt.close("all") return [activity_map]
Example #24
Source File: sgan.py From Keras-GAN with MIT License | 6 votes |
def sample_images(self, epoch): r, c = 5, 5 noise = np.random.normal(0, 1, (r * c, self.latent_dim)) gen_imgs = self.generator.predict(noise) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(r, c) cnt = 0 for i in range(r): for j in range(c): axs[i,j].imshow(gen_imgs[cnt, :,:,0], cmap='gray') axs[i,j].axis('off') cnt += 1 fig.savefig("images/mnist_%d.png" % epoch) plt.close()
Example #25
Source File: context_encoder.py From Keras-GAN with MIT License | 6 votes |
def sample_images(self, epoch, imgs): r, c = 3, 6 masked_imgs, missing_parts, (y1, y2, x1, x2) = self.mask_randomly(imgs) gen_missing = self.generator.predict(masked_imgs) imgs = 0.5 * imgs + 0.5 masked_imgs = 0.5 * masked_imgs + 0.5 gen_missing = 0.5 * gen_missing + 0.5 fig, axs = plt.subplots(r, c) for i in range(c): axs[0,i].imshow(imgs[i, :,:]) axs[0,i].axis('off') axs[1,i].imshow(masked_imgs[i, :,:]) axs[1,i].axis('off') filled_in = imgs[i].copy() filled_in[y1[i]:y2[i], x1[i]:x2[i], :] = gen_missing[i] axs[2,i].imshow(filled_in) axs[2,i].axis('off') fig.savefig("images/%d.png" % epoch) plt.close()
Example #26
Source File: ccgan.py From Keras-GAN with MIT License | 6 votes |
def sample_images(self, epoch, imgs): r, c = 3, 6 masked_imgs = self.mask_randomly(imgs) gen_imgs = self.generator.predict(masked_imgs) imgs = (imgs + 1.0) * 0.5 masked_imgs = (masked_imgs + 1.0) * 0.5 gen_imgs = (gen_imgs + 1.0) * 0.5 gen_imgs = np.where(gen_imgs < 0, 0, gen_imgs) fig, axs = plt.subplots(r, c) for i in range(c): axs[0,i].imshow(imgs[i, :, :, 0], cmap='gray') axs[0,i].axis('off') axs[1,i].imshow(masked_imgs[i, :, :, 0], cmap='gray') axs[1,i].axis('off') axs[2,i].imshow(gen_imgs[i, :, :, 0], cmap='gray') axs[2,i].axis('off') fig.savefig("images/%d.png" % epoch) plt.close()
Example #27
Source File: bigan.py From Keras-GAN with MIT License | 6 votes |
def sample_interval(self, epoch): r, c = 5, 5 z = np.random.normal(size=(25, self.latent_dim)) gen_imgs = self.generator.predict(z) gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(r, c) cnt = 0 for i in range(r): for j in range(c): axs[i,j].imshow(gen_imgs[cnt, :,:,0], cmap='gray') axs[i,j].axis('off') cnt += 1 fig.savefig("images/mnist_%d.png" % epoch) plt.close()
Example #28
Source File: cgan.py From Keras-GAN with MIT License | 6 votes |
def sample_images(self, epoch): r, c = 2, 5 noise = np.random.normal(0, 1, (r * c, 100)) sampled_labels = np.arange(0, 10).reshape(-1, 1) gen_imgs = self.generator.predict([noise, sampled_labels]) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(r, c) cnt = 0 for i in range(r): for j in range(c): axs[i,j].imshow(gen_imgs[cnt,:,:,0], cmap='gray') axs[i,j].set_title("Digit: %d" % sampled_labels[cnt]) axs[i,j].axis('off') cnt += 1 fig.savefig("images/%d.png" % epoch) plt.close()
Example #29
Source File: __init__.py From EDeN with MIT License | 5 votes |
def draw_graph_row(graphs, index=0, contract=True, n_graphs_per_line=5, size=4, xlim=None, ylim=None, **args): """draw_graph_row.""" dim = len(graphs) size_y = size size_x = size * n_graphs_per_line * args.get('size_x_to_y_ratio', 1) plt.figure(figsize=(size_x, size_y)) if xlim is not None: plt.xlim(xlim) plt.ylim(ylim) else: plt.xlim(xmax=3) for i in range(dim): plt.subplot(1, n_graphs_per_line, i + 1) graph = graphs[i] draw_graph(graph, size=None, pos=graph.graph.get('pos_dict', None), **args) if args.get('file_name', None) is None: plt.show() else: row_file_name = '%d_' % (index) + args['file_name'] plt.savefig(row_file_name, bbox_inches='tight', transparent=True, pad_inches=0) plt.close()
Example #30
Source File: coco_error_analysis.py From mmdetection with Apache License 2.0 | 5 votes |
def makeplot(rs, ps, outDir, class_name, iou_type): cs = np.vstack([ np.ones((2, 3)), np.array([.31, .51, .74]), np.array([.75, .31, .30]), np.array([.36, .90, .38]), np.array([.50, .39, .64]), np.array([1, .6, 0]) ]) areaNames = ['allarea', 'small', 'medium', 'large'] types = ['C75', 'C50', 'Loc', 'Sim', 'Oth', 'BG', 'FN'] for i in range(len(areaNames)): area_ps = ps[..., i, 0] figure_tile = iou_type + '-' + class_name + '-' + areaNames[i] aps = [ps_.mean() for ps_ in area_ps] ps_curve = [ ps_.mean(axis=1) if ps_.ndim > 1 else ps_ for ps_ in area_ps ] ps_curve.insert(0, np.zeros(ps_curve[0].shape)) fig = plt.figure() ax = plt.subplot(111) for k in range(len(types)): ax.plot(rs, ps_curve[k + 1], color=[0, 0, 0], linewidth=0.5) ax.fill_between( rs, ps_curve[k], ps_curve[k + 1], color=cs[k], label=str(f'[{aps[k]:.3f}]' + types[k])) plt.xlabel('recall') plt.ylabel('precision') plt.xlim(0, 1.) plt.ylim(0, 1.) plt.title(figure_tile) plt.legend() # plt.show() fig.savefig(outDir + f'/{figure_tile}.png') plt.close(fig)