本文整理汇总了Python中matplotlib.pyplot.get_fignums函数的典型用法代码示例。如果您正苦于以下问题:Python get_fignums函数的具体用法?Python get_fignums怎么用?Python get_fignums使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_fignums函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _setup
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())
示例2: test_plot_tfr_topo
def test_plot_tfr_topo():
"""Test plotting of TFR data."""
import matplotlib.pyplot as plt
epochs = _get_epochs()
n_freqs = 3
nave = 1
data = np.random.RandomState(0).randn(len(epochs.ch_names),
n_freqs, len(epochs.times))
tfr = AverageTFR(epochs.info, data, epochs.times, np.arange(n_freqs), nave)
plt.close('all')
fig = tfr.plot_topo(baseline=(None, 0), mode='ratio',
title='Average power', vmin=0., vmax=14.)
# test opening tfr by clicking
num_figures_before = len(plt.get_fignums())
# could use np.reshape(fig.axes[-1].images[0].get_extent(), (2, 2)).mean(1)
with pytest.warns(None): # on old mpl there is a warning
_fake_click(fig, fig.axes[0], (0.08, 0.65))
assert num_figures_before + 1 == len(plt.get_fignums())
plt.close('all')
tfr.plot([4], baseline=(None, 0), mode='ratio', show=False, title='foo')
pytest.raises(ValueError, tfr.plot, [4], yscale='lin', show=False)
# nonuniform freqs
freqs = np.logspace(*np.log10([3, 10]), num=3)
tfr = AverageTFR(epochs.info, data, epochs.times, freqs, nave)
fig = tfr.plot([4], baseline=(None, 0), mode='mean', vmax=14., show=False)
assert fig.axes[0].get_yaxis().get_scale() == 'log'
# one timesample
tfr = AverageTFR(epochs.info, data[:, :, [0]], epochs.times[[1]],
freqs, nave)
with pytest.warns(None): # matplotlib equal left/right
tfr.plot([4], baseline=None, vmax=14., show=False, yscale='linear')
# one frequency bin, log scale required: as it doesn't make sense
# to plot log scale for one value, we test whether yscale is set to linear
vmin, vmax = 0., 2.
fig, ax = plt.subplots()
tmin, tmax = epochs.times[0], epochs.times[-1]
with pytest.warns(RuntimeWarning, match='not masking'):
_imshow_tfr(ax, 3, tmin, tmax, vmin, vmax, None, tfr=data[:, [0], :],
freq=freqs[[-1]], x_label=None, y_label=None,
colorbar=False, cmap=('RdBu_r', True), yscale='log')
fig = plt.gcf()
assert fig.axes[0].get_yaxis().get_scale() == 'linear'
# ValueError when freq[0] == 0 and yscale == 'log'
these_freqs = freqs[:3].copy()
these_freqs[0] = 0
with pytest.warns(RuntimeWarning, match='not masking'):
pytest.raises(ValueError, _imshow_tfr, ax, 3, tmin, tmax, vmin, vmax,
None, tfr=data[:, :3, :], freq=these_freqs, x_label=None,
y_label=None, colorbar=False, cmap=('RdBu_r', True),
yscale='log')
示例3: decorated
def decorated():
# make sure we don't carry over bad images from former tests.
assert len(plt.get_fignums()) == 0, "no of open figs: %s -> find the last test with ' " \
"python tests.py -v' and add a '@cleanup' decorator." % \
str(plt.get_fignums())
func()
assert len(plt.get_fignums()) == len(baseline_images), "different number of " \
"baseline_images and actuall " \
"plots."
for fignum, baseline in zip(plt.get_fignums(), baseline_images):
figure = plt.figure(fignum)
_assert_same_figure_images(figure, baseline, _file, tol=tol)
示例4: load
def load(self):
inter = mp.isinteractive()
if inter: mp.ioff()
fig_list = mp.get_fignums()
if self.file != None:
with open(self.file, 'r') as f:
ps = pkl.load(f)
self.dict = ps.dict
for p in mp.get_fignums():
if p not in fig_list:
mp.close(p)
if inter: mp.ion()
示例5: test_plot_topomap_interactive
def test_plot_topomap_interactive():
"""Test interactive topomap projection plotting."""
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
evoked.pick_types(meg='mag')
evoked.info['projs'] = []
assert not evoked.proj
evoked.add_proj(compute_proj_evoked(evoked, n_mag=1))
plt.close('all')
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()
kwargs = dict(vmin=-240, vmax=240, times=[0.1], colorbar=False, axes=ax,
res=8, time_unit='s')
evoked.copy().plot_topomap(proj=False, **kwargs)
canvas.draw()
image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
assert len(plt.get_fignums()) == 1
ax.clear()
evoked.copy().plot_topomap(proj=True, **kwargs)
canvas.draw()
image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
assert not np.array_equal(image_noproj, image_proj)
assert len(plt.get_fignums()) == 1
ax.clear()
evoked.copy().plot_topomap(proj='interactive', **kwargs)
canvas.draw()
image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
assert_array_equal(image_noproj, image_interactive)
assert not np.array_equal(image_proj, image_interactive)
assert len(plt.get_fignums()) == 2
proj_fig = plt.figure(plt.get_fignums()[-1])
_fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
canvas.draw()
image_interactive_click = np.frombuffer(
canvas.tostring_rgb(), dtype='uint8')
assert_array_equal(image_proj, image_interactive_click)
assert not np.array_equal(image_noproj, image_interactive_click)
_fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
canvas.draw()
image_interactive_click = np.frombuffer(
canvas.tostring_rgb(), dtype='uint8')
assert_array_equal(image_noproj, image_interactive_click)
assert not np.array_equal(image_proj, image_interactive_click)
示例6: test_plotting
def test_plotting(self):
Options.multiprocessing=False
self.fldr.figure(figsize=(9,6))
self.fldr.each.plot()
self.assertEqual(len(plt.get_fignums()),1,"Plotting to a single figure in PlotFolder failed.")
plt.close("all")
self.fldr.plot(extra=extra)
self.assertEqual(len(plt.get_fignums()),2,"Plotting to a single figure in PlotFolder failed.")
self.ax=self.fldr[0].subplots
self.assertEqual(len(self.ax),12,"Subplots check failed.")
plt.close("all")
Options.multiprocessing=True
示例7: _image_comparison
def _image_comparison(baseline_images, extensions=["pdf", "svg", "png"], tol=11, rtol=1e-3, **kwargs):
for num, base in zip(plt.get_fignums(), baseline_images):
for ext in extensions:
fig = plt.figure(num)
fig.canvas.draw()
# fig.axes[0].set_axis_off()
# fig.set_frameon(False)
if ext in ["npz"]:
figdict = flatten_axis(fig)
np.savez_compressed(os.path.join(result_dir, "{}.{}".format(base, ext)), **figdict)
fig.savefig(
os.path.join(result_dir, "{}.{}".format(base, "png")),
transparent=True,
edgecolor="none",
facecolor="none",
# bbox='tight'
)
for num, base in zip(plt.get_fignums(), baseline_images):
for ext in extensions:
# plt.close(num)
actual = os.path.join(result_dir, "{}.{}".format(base, ext))
expected = os.path.join(baseline_dir, "{}.{}".format(base, ext))
if ext == "npz":
def do_test():
if not os.path.exists(expected):
import shutil
shutil.copy2(actual, expected)
# shutil.copy2(os.path.join(result_dir, "{}.{}".format(base, 'png')), os.path.join(baseline_dir, "{}.{}".format(base, 'png')))
raise IOError("Baseline file {} not found, copying result {}".format(expected, actual))
else:
exp_dict = dict(np.load(expected).items())
act_dict = dict(np.load(actual).items())
for name in act_dict:
if name in exp_dict:
try:
np.testing.assert_allclose(
exp_dict[name],
act_dict[name],
err_msg="Mismatch in {}.{}".format(base, name),
rtol=rtol,
**kwargs
)
except AssertionError as e:
raise SkipTest(e)
yield do_test
plt.close("all")
示例8: test_plot_topo_image_epochs
def test_plot_topo_image_epochs():
"""Test plotting of epochs image topography."""
title = 'ERF images - MNE sample data'
epochs = _get_epochs()
epochs.load_data()
cmap = mne_analyze_colormap(format='matplotlib')
data_min = epochs._data.min()
plt.close('all')
fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200,
colorbar=True, title=title, cmap=cmap)
assert epochs._data.min() == data_min
num_figures_before = len(plt.get_fignums())
_fake_click(fig, fig.axes[0], (0.08, 0.64))
assert num_figures_before + 1 == len(plt.get_fignums())
plt.close('all')
示例9: setup
def setup(self):
func = self.func
plt.close('all')
self.setup_class()
try:
matplotlib.style.use(self.style)
matplotlib.testing.set_font_settings_for_testing()
func()
assert len(plt.get_fignums()) == len(self.baseline_images), (
"Test generated {} images but there are {} baseline images"
.format(len(plt.get_fignums()), len(self.baseline_images)))
except:
# Restore original settings before raising errors.
self.teardown_class()
raise
示例10: save_all
def save_all(basename,pdf=True,png=True,single_pdf=False,close=True):
"""Save all figures"""
if not pl.get_fignums(): return
if pdf: pp = PdfPages(basename+".pdf")
for i in pl.get_fignums():
fig = pl.figure(i)
if pdf: pp.savefig(fig)
if png:
fig.patch.set_alpha(0.0)
fig.savefig(basename+"-%02d.png" % i)
if single_pdf:
fig.savefig(basename+"-%02d.pdf" % i)
if pdf: pp.close()
if close: pl.close("all")
示例11: multipage
def multipage(filename, figs=None, dpi=200):
pp = PdfPages(filename)
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()
示例12: cursor
def cursor(artists_or_axes=None, **kwargs):
"""Create a :class:`Cursor` for a list of artists or axes.
Parameters
----------
artists_or_axes : Optional[List[Union[Artist, Axes]]]
All artists in the list and all artists on any of the axes passed in
the list are selectable by the constructed :class:`Cursor`. Defaults
to all artists on any of the figures that :mod:`pyplot` is tracking.
**kwargs
Keyword arguments are passed to the :class:`Cursor` constructor.
"""
if artists_or_axes is None:
artists_or_axes = [ax
for fig in map(plt.figure, plt.get_fignums())
for ax in fig.axes]
elif not isinstance(artists_or_axes, Iterable):
artists_or_axes = [artists_or_axes]
artists = []
for entry in artists_or_axes:
if isinstance(entry, Axes):
ax = entry
artists.extend(ax.lines + ax.patches + ax.collections + ax.images)
# No need to extend with each container (ax.containers): the
# contained artists have already been added.
else:
artist = entry
artists.append(artist)
return Cursor(artists, **kwargs)
示例13: test_hist_by_no_extra_plots
def test_hist_by_no_extra_plots(self):
import matplotlib.pyplot as plt
n = 10
df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n),
'height': random.normal(66, 4, size=n)})
axes = df.height.hist(by=df.gender)
self.assertEqual(len(plt.get_fignums()), 1)
示例14: show_pdf
def show_pdf(filename,width=0.5,aspect=None):
"""
Displays the specified pdf file in a ipython/jupiter notebook.
The width is given as screen width, the height is given via the
aspect ratio.
Arguments:
----------
filename : string
The path of the pdf to be shown
Keywords:
---------
width : float
The width where 1 = full width
aspect : float
The aspect ratio width/height. Defaults to last figure's
aspect ratio or to 4./3. if no figure present.
Returns:
--------
A HTML object
"""
if aspect is None:
if plt.get_fignums()==[]:
aspect = aspect or 4./3.
else:
aspect = plt.gcf().get_size_inches()
aspect = aspect[0]/aspect[1]
return HTML('<div style="position:relative;width:{:g}%;height:0;padding-bottom:{:g}%">'.format(width*100,width*100/aspect+2)+\
'<iframe src="'+filename+'" style="width:100%;height:100%"></iframe></div>')
示例15: _init_figure
def _init_figure(self, **kwargs):
from matplotlib import pyplot
# add new attributes
self.colorbars = []
self._coloraxes = []
# create Figure
num = kwargs.pop('num', max(pyplot.get_fignums() or {0}) + 1)
self._parse_subplotpars(kwargs)
super(Plot, self).__init__(**kwargs)
self.number = num
# add interactivity (scraped from pyplot.figure())
backend_mod = get_backend_mod()
try:
manager = backend_mod.new_figure_manager_given_figure(num, self)
except AttributeError:
upstream_mod = importlib.import_module(
pyplot.new_figure_manager.__module__)
canvas = upstream_mod.FigureCanvasBase(self)
manager = upstream_mod.FigureManagerBase(canvas, 1)
manager._cidgcf = manager.canvas.mpl_connect(
'button_press_event',
lambda ev: _pylab_helpers.Gcf.set_active(manager))
_pylab_helpers.Gcf.set_active(manager)
pyplot.draw_if_interactive()