我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用matplotlib.pyplot.get_fignums()。
def savefigs(name="fig", DIR="/tmp/", size=None, bbox_inches="tight", ending=".eps"): if not DIR.endswith("/"): DIR = DIR + "/" assertdir(DIR) if len(plt.get_fignums()) == 1: num = plt.get_fignums()[0] fig = plt.figure(num) label = fig.get_label() label = "" if label=="" else "_"+label if size is not None: fig.set_size_inches(size) fig.savefig(DIR + name + label + ending, bbox_inches=bbox_inches) return for num in plt.get_fignums(): fig = plt.figure(num) label = fig.get_label() label = str(num) if label=="" else label if size is not None: fig.set_size_inches(size) fig.savefig(DIR + name + "_" + label + ending, bbox_inches=bbox_inches)
def plot_scatter_real_time(solution_list: List[S], evaluations: int, computing_time: float, animation_speed: float, plot_title="Pareto frontier (real-time)"): """ Plot non-dominated solutions in real-time. For problems with TWO variables. """ global sc if not plt.get_fignums(): # The first time, set up plot sc = ScatterPlot(plot_title=plot_title, animation_speed=animation_speed) sc.simple_plot(solution_list=solution_list, save=False) else: sc.update(solution_list=solution_list, evaluations=evaluations, computing_time=computing_time)
def _setup(): # The baseline images are created in this locale, so we should use # it during all of the tests. try: locale.setlocale(locale.LC_ALL, str('en_US.UTF-8')) except locale.Error: try: locale.setlocale(locale.LC_ALL, str('English_United States.1252')) except locale.Error: warnings.warn( "Could not set locale to English/United States. " "Some date-related tests may fail") plt.switch_backend('Agg') # use Agg backend for these test if mpl.get_backend().lower() != "agg": msg = ("Using a wrong matplotlib backend ({0}), " "which will not produce proper images") raise Exception(msg.format(mpl.get_backend())) # These settings *must* be hardcoded for running the comparison # tests mpl.rcdefaults() # Start with all defaults mpl.rcParams['text.hinting'] = True mpl.rcParams['text.antialiased'] = True mpl.rcParams['text.hinting_factor'] = 8 # make sure we don't carry over bad plots from former tests msg = ("no of open figs: {} -> find the last test with ' " "python tests.py -v' and add a '@cleanup' decorator.") assert len(plt.get_fignums()) == 0, msg.format(plt.get_fignums())
def test_ggsave_closes_plot(): assert plt.get_fignums() == [], "There are unsaved test plots" fn = next(filename_gen) p.save(fn) assert_exist_and_clean(fn, "exist") assert plt.get_fignums() == [], "ggplot.save did not close the plot"
def load_figure(d, new_fig=True): """Create a figure from what is returned by :meth:`inspect_figure`""" import matplotlib.pyplot as plt subplotpars = d.pop('subplotpars', None) if subplotpars is not None: subplotpars.pop('validate', None) subplotpars = mfig.SubplotParams(**subplotpars) if new_fig: nums = plt.get_fignums() if d.get('num') in nums: d['num'] = next( i for i in range(max(plt.get_fignums()) + 1, 0, -1) if i not in nums) return plt.figure(subplotpars=subplotpars, **d)
def test_one_subplot(self): plt.close('all') axes = psy.multiple_subplots() self.assertEqual(len(axes), 1) self.assertEqual(plt.get_fignums(), [1]) self.assertEqual(len(plt.gcf().axes), 1) self.assertIs(axes[0], plt.gcf().axes[0]) plt.close('all')
def test_multiple_subplots(self): plt.close('all') axes = psy.multiple_subplots(2, 2, 3, 5) self.assertEqual(len(axes), 5) self.assertEqual(plt.get_fignums(), [1, 2]) self.assertEqual(len(plt.figure(1).axes), 3) self.assertEqual(len(plt.figure(2).axes), 2) it_ax = iter(axes) for ax2 in chain(plt.figure(1).axes, plt.figure(2).axes): self.assertIs(next(it_ax), ax2) plt.close('all')
def saveplots(name="plot", meta=None, uid=False): # collect data from every open figure plots = [] figs = map(plt.figure, plt.get_fignums()) for fig in figs: for ax in fig.axes: plot = dict( xlabel = ax.get_xlabel(), ylabel = ax.get_ylabel(), xscale = ax.get_xscale(), yscale = ax.get_yscale(), data = []) for line in ax.lines: x, y = line.get_data() marker = line.get_marker() if marker == "None": marker = "" data = dict( x = x, y = y, style = marker + line.get_linestyle(), label = line.get_label()) plot["data"].append(data) plots.append(plot) # add metadata if provided meta = {} if meta is None else meta data = dict(plots=plots, meta=meta) # save to txt file in DATADIR DIR = os.path.join(DATADIR, "plots") name = name + "_" + str(unique_id()) if uid else name save_dict(data, DIR, name) return plots
def replot_image(self): if not plt.get_fignums(): self.plot() z = self.get_data() self.image.set_data(z) self.replot_peaks() plt.draw()
def replot_peaks(self): if not plt.get_fignums(): self.plot() peaks = self.get_peaks() self.pts.set_xdata(peaks[:, 1]) self.pts.set_ydata(peaks[:, 0]) plt.draw()
def close(fignum=None): from matplotlib.pyplot import get_fignums, close as _close if fignum is None: for fignum in get_fignums(): _close(fignum) else: _close(fignum)
def plot_series(data, kind='line', ax=None, # Series unique figsize=None, use_index=True, title=None, grid=None, legend=False, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, # Series unique **kwds): import matplotlib.pyplot as plt """ If no axes is specified, check whether there are existing figures If there is no existing figures, _gca() will create a figure with the default figsize, causing the figsize=parameter to be ignored. """ if ax is None and len(plt.get_fignums()) > 0: ax = _gca() ax = MPLPlot._get_ax_layer(ax) return _plot(data, kind=kind, ax=ax, figsize=figsize, use_index=use_index, title=title, grid=grid, legend=legend, style=style, logx=logx, logy=logy, loglog=loglog, xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, rot=rot, fontsize=fontsize, colormap=colormap, table=table, yerr=yerr, xerr=xerr, label=label, secondary_y=secondary_y, **kwds)
def plot_save(path, figs=None, dpi=180, tight_plot=False, clear_all=True, log=True): """ Parameters ---------- clear_all: bool if True, remove all saved figures from current figure list in matplotlib """ try: from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt if tight_plot: plt.tight_layout() if os.path.exists(path) and os.path.isfile(path): os.remove(path) pp = PdfPages(path) if figs is None: figs = [plt.figure(n) for n in plt.get_fignums()] for fig in figs: fig.savefig(pp, format='pdf', bbox_inches="tight") pp.close() if log: sys.stderr.write('Saved pdf figures to:%s \n' % str(path)) if clear_all: plt.close('all') except Exception as e: sys.stderr.write('Cannot save figures to pdf, error:%s \n' % str(e))
def get_new_fignum(): fignums = plt.get_fignums() if fignums: return max(fignums) + 1 else: return 1
def run(): plt.ion() laser = HokuyoLX() ax = plt.subplot(111, projection='polar') plot = ax.scatter([0, 1], [0, 1], s=5, c=[IMIN, IMAX], cmap=plt.cm.Greys_r, lw=0) text = plt.text(0, 1, '', transform=ax.transAxes) ax.set_rmax(DMAX) ax.grid(True) plt.show() while plt.get_fignums(): update(laser, plot, text) laser.close()
def run(): plt.ion() laser = HokuyoLX() ax = plt.subplot(111, projection='polar') plot = ax.plot([], [], '.')[0] text = plt.text(0, 1, '', transform=ax.transAxes) ax.set_rmax(DMAX) ax.grid(True) plt.show() while plt.get_fignums(): update(laser, plot, text) laser.close()
def tight_layout_and_grid_all(isVerbose=True): ''' Activates tight_layout for all open axes ''' fignums = plt.get_fignums() for num in fignums: if isVerbose: print 'Formatting figure %i\r' % num, fig = plt.figure(num) if len(fig.get_axes()) > 0: for ax in fig.get_axes(): ax.grid(True) plt.draw() plt.tight_layout() plt.draw()
def clear_all(): ''' Clears all figures currently displayed ''' fignums = plt.get_fignums() for num in fignums: plt.figure(num) plt.clf() # ##############################################################################
def clear_all(): ''' Clears all figures currently displayed ''' fignums = plt.get_fignums() for num in fignums: plt.figure(num) plt.clf()
def cleanup(): for fig in map(plt.figure, plt.get_fignums()): fig.clf()
def plot_save(path, figs=None, dpi=300): try: from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt pp = PdfPages(path) if figs is None: figs = [plt.figure(n) for n in plt.get_fignums()] for fig in figs: fig.savefig(pp, format='pdf') pp.close() logger.info('Saved pdf figures to:%s' % str(path)) except Exception, e: logger.error('Cannot save figures to pdf, error:%s' % str(e))
def save_figures(image_path, fig_count, gallery_conf): """Save all open matplotlib figures of the example code-block Parameters ---------- image_path : str Path where plots are saved (format string which accepts figure number) fig_count : int Previous figure number count. Figure number add from this number gallery_conf : dict Contains the configuration of Sphinx-Gallery Returns ------- images_rst : str rst code to embed the images in the document fig_num : int number of figures saved """ figure_list = [] for fig_num in plt.get_fignums(): # Set the fig_num figure as the current figure as we can't # save a figure that's not the current figure. fig = plt.figure(fig_num) kwargs = {} to_rgba = matplotlib.colors.colorConverter.to_rgba for attr in ['facecolor', 'edgecolor']: fig_attr = getattr(fig, 'get_' + attr)() default_attr = matplotlib.rcParams['figure.' + attr] if to_rgba(fig_attr) != to_rgba(default_attr): kwargs[attr] = fig_attr current_fig = image_path.format(fig_count + fig_num) fig.savefig(current_fig, **kwargs) figure_list.append(current_fig) if gallery_conf.get('find_mayavi_figures', False): from mayavi import mlab e = mlab.get_engine() last_matplotlib_fig_num = fig_count + len(figure_list) total_fig_num = last_matplotlib_fig_num + len(e.scenes) mayavi_fig_nums = range(last_matplotlib_fig_num + 1, total_fig_num + 1) for scene, mayavi_fig_num in zip(e.scenes, mayavi_fig_nums): current_fig = image_path.format(mayavi_fig_num) mlab.savefig(current_fig, figure=scene) # make sure the image is not too large scale_image(current_fig, current_fig, 850, 999) figure_list.append(current_fig) mlab.close(all=True) return figure_rst(figure_list, gallery_conf['src_dir'])