本文整理汇总了Python中matplotlib.pyplot.get_backend函数的典型用法代码示例。如果您正苦于以下问题:Python get_backend函数的具体用法?Python get_backend怎么用?Python get_backend使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_backend函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fg
def fg(fig=None):
"""Raise figure to foreground."""
plt.figure((fig or plt.gcf()).number)
if plt.get_backend()[0:2].lower() == 'qt':
plt.get_current_fig_manager().window.activateWindow()
plt.get_current_fig_manager().window.raise_()
elif plt.get_backend()[0:2].lower() == 'wx':
plt.get_current_fig_manager().window.Raise()
示例2: __init__
def __init__(self, calibrationfile, addon_path=None):
# the plotting backend switch is usually required
try:
self.load_calibration(calibrationfile)
except FileNotFoundError:
self.rect = None
# needed to reference the CommandCam.exe program on Windows
self.addon_path = addon_path
print('Plotting backend:', plt.get_backend())
print('Switching to Agg...')
plt.switch_backend('Agg')
print('Plotting backend:', plt.get_backend())
示例3: radio_overlay_b1555
def radio_overlay_b1555():
"""
Plots the NIR AO image in greyscale, and then overlays contours
from two radio data sets: MERLIN and VLBA
"""
""" Set the input file names """
aoim = '../data/B1555_nirc2_n_Kp_6x6.fits'
merlin_im = '../data/1555_merlin_5ghz.fits'
vlbi_im = '../data/B1555_vlbi_fix_astrom.fits'
""" Hardwire rms levels if needed """
rms_vlbi = 0.0001
""" Set the image center, origin location, and size """
racent = 239.29968
deccent = 37.359921
zeropos = (0.2276,0.2194)
imsize = 1.2 # Value in arcsec
""" Make the overlay plot """
imf.overlay_contours(aoim,merlin_im,racent,deccent,imsize,
showradec=False,fmax=6.,zeropos=zeropos,
infile3=vlbi_im,rms3=rms_vlbi,ccolor3='b')
""" Set up the font """
if plt.get_backend() == 'MacOSX':
font = {'style' : 'normal',
'color' : 'black',
'weight' : 'bold',
'size' : 24,
}
else:
print 'Using backend %s' % (plt.get_backend())
font = {'family' : 'serif',
'style' : 'normal',
'color' : 'black',
'weight' : 'bold',
'size' : 24,
}
"""
Label the lensed images, taking into account a possible shift in origin,
which would be set by the zeropos position
"""
labx = n.array([0.33, 0.17, -0.25, 0.16])
laby = n.array([0.30, 0.36, 0.25, -0.24])
labx -= zeropos[0]
laby -= zeropos[1]
labt = ['A', 'B', 'C', 'D']
for i in range(len(labx)):
plt.text(labx[i],laby[i],labt[i],fontdict=font)
示例4: set_up_plot
def set_up_plot(self, settings=None):
self.plot = Plot()
if settings is not None:
for key in settings:
self.plot.settings[key] = settings[key]
self.settings['plot'] = self.plot.settings
n_rows = self.plot.settings['n_rows']
n_cols = self.plot.settings['n_cols']
if n_rows is not None and n_cols is not None:
print '\nSetting up {0:d}x{1:d} plot.'.format(n_rows, n_cols)
else:
e_str = 'Number of {0:s} must be an integer > 0.'
n_rows, n_cols = (0, 0)
while n_rows < 1 or n_cols < 1:
n_rows = utils.get_input_integer( \
'\nNumber of subplot rows?\n> ',
error_text=e_str.format('rows'))[0]
n_cols = utils.get_input_integer( \
'Number of subplot columns?\n> ',
error_text=e_str.format('columns'))[0]
if n_rows < 1 or n_cols < 1:
print 'Must have > 0 rows and columns.'
self.plot.set_up_plot_grid(n_rows, n_cols)
#self.plot.plot_grid.tight_layout(self.plot.figure)
self.plot.figure.set_tight_layout(True)
plt.show(block=False)
print '(If you cannot see the plot, try changing the '
print 'matplotlib backend. Current backend is ' + \
plt.get_backend() + '.)'
示例5: __init__
def __init__(self, f=None, reader=None, interactive=True, toolbar=True,
*args, **kwargs):
# Read in data
if f is not None:
if reader is None:
self.reader = DefaultReader(f, *args, **kwargs)
else:
self.reader = reader(f, *args, **kwargs)
self.data = self.reader.init_data(*args, **kwargs)
self._initialized = True
else:
self.reader = None
self._initialized = False
# `interactive` determines if the MPL event loop is used or a
# raw figure is made. Set to False if using an external event handler,
# e.g. if embedding in a separate program.
self.interactive = interactive
# Static version is not threaded, but want to make sure any subclasses
# are thread-safe
self.lock = threading.RLock()
# Need to keep track of the backend, since not all backends support
# all update schemes
self._backend = plt.get_backend().lower()
self.fig = self._create_fig(toolbar=toolbar)
self.axes = None
self.canvas = self.fig.canvas
self.mode = 'none'
self._plotdict = {'autoscalex': True, # Autoscale is meaningless in
'autoscaley': True, # Static, but useful in RT
'windowsize': None}
示例6: movie
def movie(self,di=10, coord='latlon',land="nice", heatmap=False):
curr_backend = plt.get_backend()
plt.switch_backend('Agg')
FFMpegWriter = animation.writers['ffmpeg']
metadata = dict(title='%s %s' % (self.projname, self.casename),
artist='pytraj',
comment='https://github.com/TRACMASS/pytraj')
writer = FFMpegWriter(fps=15, metadata=metadata)
fig = plt.figure()
with writer.saving(fig, "traj_test.mp4", 200):
for part in self.partvec:
self.load(part=part)
jdvec = np.sort(self.jdvec)
for jd in jdvec:
print part, jdvec[-1] - jd, len(self.jd[self.jd==jd])
if len(self.jd[self.jd==jd]) <= 1: continue
if jd/di == float(jd)/di:
if heatmap == True:
self.heatmap(log=True, jd=jd)
else:
self.scatter(jd=jd, coord=coord, land=land)
writer.grab_frame()
plt.switch_backend(curr_backend)
示例7: __init__
def __init__(self, fig, event_source=None, blit=False):
self._fig = fig
if blit and plt.get_backend().lower() == 'macosx':
raise BackendError('''The current backend is 'MacOSX'
and may go into an infinite loop with blit turned on. Either
turn off blit or use an alternate backend, for example, like
'TKAgg', using the following prepended to your source code:
import matplotlib
matplotlib.use('TKAgg')
''')
self._blit = blit
# These are the basics of the animation. The frame sequence represents
# information for each frame of the animation and depends on how the
# drawing is handled by the subclasses. The event source fires events
# that cause the frame sequence to be iterated.
self.frame_seq = self.new_frame_seq()
self.event_source = event_source
# Clear the initial frame
self._init_draw()
# Instead of starting the event source now, we connect to the figure's
# draw_event, so that we only start once the figure has been drawn.
self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
# Connect to the figure's close_event so that we don't continue to
# fire events and try to draw to a deleted figure.
self._close_id = self._fig.canvas.mpl_connect('close_event', self._stop)
if blit:
self._setup_blit()
示例8: on_window_close
def on_window_close(figure, function):
"""Connects a close figure signal to a given function
Parameters
----------
figure : mpl figure instance
function : function
"""
window = figure.canvas.manager.window
backend = plt.get_backend()
if backend == 'GTKAgg':
def function_wrapper(*args):
function()
window.connect('destroy', function_wrapper)
elif backend == 'WXAgg':
# In linux the following code produces a segmentation fault
# so it is enabled only for Windows
import wx
def function_wrapper(event):
function()
plt.close(figure)
window.Bind(wx.EVT_CLOSE, function_wrapper)
elif backend == 'TkAgg':
def function_wrapper(*args):
function()
figure.canvas.manager.window.bind("<Destroy>", function_wrapper)
elif backend == 'Qt4Agg':
from PyQt4.QtCore import SIGNAL
window = figure.canvas.manager.window
window.connect(window, SIGNAL('destroyed()'), function)
示例9: matplotlib_config
def matplotlib_config():
"""Configure matplotlib for viz tests."""
import matplotlib
# "force" should not really be necessary but should not hurt
kwargs = dict()
if 'warn' in _get_args(matplotlib.use):
kwargs['warn'] = False
matplotlib.use('agg', force=True, **kwargs) # don't pop up windows
import matplotlib.pyplot as plt
assert plt.get_backend() == 'agg'
# overwrite some params that can horribly slow down tests that
# users might have changed locally (but should not otherwise affect
# functionality)
plt.ioff()
plt.rcParams['figure.dpi'] = 100
try:
from traits.etsconfig.api import ETSConfig
except Exception:
pass
else:
ETSConfig.toolkit = 'qt4'
try:
with warnings.catch_warnings(record=True): # traits
from mayavi import mlab
except Exception:
pass
else:
mlab.options.backend = 'test'
示例10: wrapped
def wrapped(*args, **kwargs):
orig_backend = plt.get_backend()
plt.switch_backend('agg')
mpl_setup()
if pyplot_helpers.Gcf.figs:
warnings.warn('Figures existed before running the %s %s test.'
' All figures should be closed after they run. '
'They will be closed automatically now.' %
(mod_name, test_name))
pyplot_helpers.Gcf.destroy_all()
if MPL_VERSION >= '2':
style_context = mpl.style.context
else:
@contextlib.contextmanager
def style_context(style, after_reset=False):
yield
with style_context(self.style):
r = test_func(*args, **kwargs)
fig_managers = pyplot_helpers.Gcf._activeQue
figures = [manager.canvas.figure for manager in fig_managers]
try:
self.run_figure_comparisons(figures, test_name=mod_name)
finally:
for figure in figures:
pyplot_helpers.Gcf.destroy_fig(figure)
plt.switch_backend(orig_backend)
return r
示例11: test
def test(show=False, coverage=False):
"""Test all code examples in docstrings using pytest."""
try:
import pytest
except ImportError:
raise ImportError("pytest is required to run test suite. " + "Try 'sudo pip install pytest'.")
from matplotlib import pyplot as plt
from pygimli.utils import opt_import
pc = opt_import("pytest_cov", "create a coverage report")
old_backend = plt.get_backend()
if not show:
plt.switch_backend("Agg")
cwd = __path__[0]
cfg = os.path.join(cwd, "../tests/setup.cfg")
cmd = ""
if os.path.exists(cfg):
cmd += "-c %s " % cfg
if pc and coverage:
cmd += "--cov pygimli --cov-report coveralls --cov-report html " + "--cov-config %s " % cfg.replace(
"setup.cfg", ".coveragerc"
)
cmd += "%s" % cwd
try:
pytest.main(cmd)
finally:
plt.switch_backend(old_backend)
示例12: start_jobs
def start_jobs():
"""
Restores the plots if requested and if the persistent files exist and
starts the qt timer of the 1st plot.
"""
for plot in _plots:
if plot.persistentName:
plot.restore_plots()
plot.fig.canvas.set_window_title(plot.title)
runCardVals.iteration = np.long(0)
noTimer = len(_plots) == 0 or\
(plt.get_backend().lower() in (x.lower() for x in
mpl.rcsetup.non_interactive_bk))
if noTimer:
print("The job is running... ")
while True:
msg = '{0} of {1}'.format(
runCardVals.iteration+1, runCardVals.repeats)
if os.name == 'posix':
sys.stdout.write("\r\x1b[K " + msg)
else:
sys.stdout.write("\r ")
print(msg+' ')
sys.stdout.flush()
res = dispatch_jobs()
if res:
return
else:
plot = _plots[0]
plot.areProcessAlreadyRunning = False
plot.timer = plot.fig.canvas.new_timer()
plot.timer.add_callback(plot.timer_callback)
plot.timer.start()
示例13: _setup_timers
def _setup_timers(self):
"""Set up timers to limit call-rate and avoid "flickering" effect."""
self.timer_expired = {}
self.ax_timer = {}
# Timer to control call-rate.
def expire_func(ax, *args, **kwargs):
self.timer_expired[ax] = True
# Return True to keep callback
return True
for ax in self.axes:
interval = 300 if self.hover else 100
try:
self.ax_timer[ax] = ax.figure.canvas.new_timer(
interval=interval,
callbacks=[(expire_func, [ax], {})],
)
except AttributeError:
# Some backends don't have timers at all! Starting/stopping
# will raise an AttributeError, but this is caught regardless
# as some backend's timers don't support start/stop.
self.ax_timer[ax] = None
try:
if plt.get_backend() != 'MacOSX':
# Single-shot timers on the OSX backend segfault!
self.ax_timer[ax].single_shot = True
except AttributeError:
# For mpl <= 1.3.1 with the wxAgg backend, setting the
# timer to be single_shot will raise an error that can be
# safely ignored.
pass
self.timer_expired[ax] = True
示例14: movie
def movie(self, fldname, jd1=None, jd2=None, jdvec=None, fps=10, **kwargs):
curr_backend = plt.get_backend()
plt.switch_backend('Agg')
FFMpegWriter = animation.writers['ffmpeg']
metadata = dict(title='%s' % (self.projname),
artist=self.projname,
comment='https://github.com/brorfred/njord')
writer = FFMpegWriter(fps=fps, metadata=metadata,
extra_args=['-vcodec', 'libx264',"-pix_fmt", "yuv420p"])
jdvec = self.get_tvec(jd1, jd2) if jdvec is None else jdvec
fig = plt.figure()
with writer.saving(fig, "%s.mp4" % self.projname, 200):
for jd in jdvec:
pl.clf()
print(pl.num2date(jd).strftime("%Y-%m-%d %H:%M load "), end="")
sys.stdout.flush()
try:
fld= self.get_field(fldname, jd=jd)
except:
print("not downloaded" % jd)
continue
print("plot ", end="")
sys.stdout.flush()
self.pcolor(fld, **kwargs)
pl.title(pl.num2date(jd).strftime("%Y-%m-%d %H:%M"))
print("write")
writer.grab_frame()#bbox_inches="tight", pad_inches=0)
plt.switch_backend(curr_backend)
示例15: _set_backend
def _set_backend():
"""Choose the backend and get the GUI elements needed for it."""
backend = _p.get_backend()
if not backend.startswith('GTK'):
if _p.rcParams['backend_fallback']:
if backend.endswith('Agg'):
backend = 'GTKAgg'
elif backend.endswith('Cairo'):
backend = 'GTKCairo'
else:
backend = 'GTK'
else:
raise NotImplementedError, """
You must use a GTK-based backend with refigure. Adjust
your matplotlibrc file, or before importing refigure run
>>> from matplotlib import use
>>> use( < 'GTK' | 'GTKAgg' | 'GTKCairo' > )
"""
gui_elements = ['FigureCanvas'+backend, 'NavigationToolbar2'+backend]
if backend == 'GTKCairo':
gui_elements[1] = 'NavigationToolbar2GTK'
temp = __import__('matplotlib.backends.backend_' + backend.lower(),
globals(), locals(), gui_elements)
canvas = getattr(temp, gui_elements[0])
toolbar = getattr(temp, gui_elements[1])
return backend, canvas, toolbar