本文整理汇总了Python中matplotlib.get_backend函数的典型用法代码示例。如果您正苦于以下问题:Python get_backend函数的具体用法?Python get_backend怎么用?Python get_backend使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_backend函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _init_matplotlib
def _init_matplotlib():
import matplotlib as mpl
import utool
backend = mpl.get_backend()
if not sys.platform.startswith('win32') and not sys.platform.startswith('darwin') and os.environ.get('DISPLAY', None) is None:
# Write to files if we cannot display
TARGET_BACKEND = 'PDF'
else:
TARGET_BACKEND = 'Qt4Agg'
if utool.in_main_process():
if not utool.QUIET and utool.VERBOSE:
print('--- INIT MPL---')
print('[main] current backend is: %r' % backend)
print('[main] mpl.use(%r)' % TARGET_BACKEND)
if backend != TARGET_BACKEND:
mpl.use(TARGET_BACKEND, warn=True, force=True)
backend = mpl.get_backend()
if not utool.QUIET and utool.VERBOSE:
print('[main] current backend is: %r' % backend)
if utool.get_flag('--notoolbar'):
toolbar = 'None'
else:
toolbar = 'toolbar2'
mpl.rcParams['toolbar'] = toolbar
mpl.rc('text', usetex=False)
mpl_keypress_shortcuts = [key for key in mpl.rcParams.keys() if key.find('keymap') == 0]
for key in mpl_keypress_shortcuts:
mpl.rcParams[key] = ''
开发者ID:byteyoo,项目名称:ibeis,代码行数:28,代码来源:main_module.py
示例2: Show
def Show():
"""
Show all figures and start the event loop if necessary
"""
managers = GlobalFigureManager.get_all_fig_managers()
if not managers:
return
for manager in managers:
manager.show()
# Hack: determine at runtime whether we are
# inside ipython in pylab mode.
from matplotlib import pyplot
try:
ipython_pylab = not pyplot.show._needmain
# IPython versions >= 0.10 tack the _needmain
# attribute onto pyplot.show, and always set
# it to False, when in %pylab mode.
ipython_pylab = ipython_pylab and mpl.get_backend() != 'WebAgg'
# TODO: The above is a hack to get the WebAgg backend
# working with ipython's `%pylab` mode until proper
# integration is implemented.
except AttributeError:
ipython_pylab = False
# Leave the following as a separate step in case we
# want to control this behavior with an rcParam.
if ipython_pylab:
return
if not mpl.is_interactive() or mpl.get_backend() == 'WebAgg':
QAppThreadCall(mainloop)()
开发者ID:mantidproject,项目名称:mslice,代码行数:34,代码来源:_mslice_commands.py
示例3: _setup
def _setup():
# The baseline images are created in this locale, so we should use
# it during all of the tests.
import locale
import warnings
from matplotlib.backends import backend_agg, backend_pdf, backend_svg
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")
mpl.use('Agg', warn=False) # use Agg backend for these tests
if mpl.get_backend().lower() != "agg":
raise Exception(("Using a wrong matplotlib backend ({0}), which will not produce proper "
"images").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
# Clear the font caches. Otherwise, the hinting mode can travel
# from one test to another.
backend_agg.RendererAgg._fontd.clear()
backend_pdf.RendererPdf.truetype_font_cache.clear()
backend_svg.RendererSVG.fontd.clear()
开发者ID:janschulz,项目名称:ggplot,代码行数:34,代码来源:__init__.py
示例4: save_figure_helper
def save_figure_helper(fpath):
if matplotlib.get_backend() == 'pdf':
final_path = fpath + '.pdf'
pylab.savefig(final_path)
pylab.close()
print('Written: %s'%final_path)
print('Converting to eps...')
os.system('pdftops -eps ' + final_path)
os.rename(fpath+'.eps', fpath+'_.eps') #missing bounding box
os.system('eps2eps ' + fpath+'_.eps' + ' ' + fpath+'.eps')
os.remove(fpath+'_.eps')
elif matplotlib.get_backend() == 'ps':
final_path = fpath + '.eps'
pylab.savefig(final_path)
pylab.close()
print('Written: %s'%final_path)
print('Converting to pdf...')
os.system('epstopdf ' + final_path)
else:
print('Trying to save to PDF. Backend: %s'%matplotlib.get_backend())
final_path = fpath + '.pdf'
pylab.savefig(final_path)
pylab.close()
print('Written: %s'%final_path)
subprocess.call(['xdg-open', final_path])
开发者ID:clstaudt,项目名称:musketeer,代码行数:25,代码来源:testers.py
示例5: do_ui_pause
def do_ui_pause(self, prompt=None):
"""Make a UI pause without regard to the current pause state."""
if prompt is None:
prompt = "Paused. Press ENTER to continue..."
if not plt.get_fignums(): # empty list: no figures are open
input(prompt)
else: # a figure is open
if matplotlib.get_backend().upper().startswith("GTK"):
title_before = plt.gcf().canvas.get_toplevel().get_title()
elif matplotlib.get_backend().upper().startswith("TK"):
title_before = plt.gcf().canvas.get_tk_widget().winfo_toplevel().wm_title()
elif matplotlib.get_backend().upper().startswith("WX"):
title_before = plt.gcf().canvas.GetTopLevelParent().GetTitle()
elif matplotlib.get_backend().upper().startswith("QT"):
title_before = str(plt.gcf().canvas.topLevelWidget().windowTitle())
else:
title_before = "Figure %d" % plt.gcf().number
while True: # wait until a key is pressed. Blink the title meanwhile.
plt.gcf().canvas.set_window_title(prompt)
result = plt.gcf().waitforbuttonpress(1)
if result: # waitforbuttonpress returns True for keypress, False for mouse click and None for timeout
break
plt.gcf().canvas.set_window_title(title_before)
result = plt.gcf().waitforbuttonpress(1)
if result: # waitforbuttonpress returns True for keypress, False for mouse click and None for timeout
break
plt.gcf().canvas.set_window_title(title_before)
开发者ID:awacha,项目名称:sastool,代码行数:27,代码来源:pauser.py
示例6: ensure_mpl_backend
def ensure_mpl_backend(backend=None):
"""
Tries to select the matplotlib backend.
Raises EnvironmentError, if the desired backend is valid
but could not be selected.
If `backend` is None, either 'agg' or 'wxagg' is chosen,
depending on whether a display is present (on Linux and Darwin).
For other platforms, 'wxagg' is always the default.
Returns the selected backend as given by matplotlib.get_backend().
"""
if backend is None:
import platform
import os
if (
platform.system() in ('Linux', 'Darwin') and not
'DISPLAY' in os.environ
):
backend = 'agg'
else:
backend = 'wxagg'
import matplotlib
active_backend = matplotlib.get_backend()
if active_backend.lower() != backend.lower():
matplotlib.use(backend)
active_backend = matplotlib.get_backend()
if active_backend.lower() != backend.lower():
raise EnvironmentError(
"Could not select matplotlib backend '%s' ('%s' is active)!" \
% (backend, active_backend)
)
return active_backend
开发者ID:GitEdit,项目名称:pyphant1,代码行数:32,代码来源:__init__.py
示例7: __init__
def __init__(self, work_dir=None, backend='TkAgg'):
if work_dir != None and os.path.exists(work_dir):
self.__WORK_DIR__ = work_dir
else:
self.__WORK_DIR__ = os.getcwd()
try:
import matplotlib
if backend in self.__INTERACTIVE_BACKENDS__:
matplotlib.use(backend, warn=False)
self.__BACKEND__ = backend
if not __SILENT_START__:
print(('Matplotlib backend set to: \"{}\"'.format(backend)))
else:
if backend in [None, 'None', 'none']:
print(('Matplotlib backend not set, using: \"{}\"'.format(matplotlib.get_backend())))
self.__BACKEND__ = matplotlib.get_backend()
else:
matplotlib.use('TkAgg', warn=False)
self.__BACKEND__ = 'TkAgg'
print(('Matplotlib \"{}\" backend not set, defaulting to: \"{}\"'.format(backend, 'TkAgg')))
#if self.__ENABLE_HTML5__:
#matplotlib.use('module://mplh5canvas.backend_h5canvas') # HTML5
#else:
#matplotlib.use('TKagg', warn=False)
except Exception as ex:
print(ex)
print("\nPySCeS defaults to matplotlib's TKagg backend if not specified in the user conficuration file, set \"matplotlib_backend = <backend>\" ")
from matplotlib import pyplot
from matplotlib import pylab
## self.pyplot = pyplot
self.pyplot = pylab
if self.__MODE_INTERACTIVE__: self.pyplot.ion()
self._setNewFigureGenerator(self.MAX_OPEN_WINDOWS)
开发者ID:PySCeS,项目名称:pysces,代码行数:35,代码来源:PyscesPlot2.py
示例8: _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())
开发者ID:jwhendy,项目名称:plotnine,代码行数:30,代码来源:conftest.py
示例9: _setup_matplotlib
def _setup_matplotlib ():
import matplotlib, os
if matplotlib.get_backend () == 'MacOSX':
matplotlib.use ('TkAgg')
if 'DISPLAY' not in os.environ and matplotlib.get_backend () == 'TkAgg':
matplotlib.use ('Agg')
开发者ID:aimran,项目名称:pwpy,代码行数:7,代码来源:casaenv.py
示例10: test_create_figure
def test_create_figure():
if matplotlib.get_backend() == "agg":
pytest.xfail("{} backend does not support on_close event.".format(
matplotlib.get_backend()))
dummy_function = Mock()
fig = utils.create_figure(window_title="test title",
_on_figure_window_close=dummy_function)
assert isinstance(fig, matplotlib.figure.Figure) == True
matplotlib.pyplot.close(fig)
dummy_function.assert_called_once_with()
开发者ID:woozey,项目名称:hyperspy,代码行数:11,代码来源:test_utils.py
示例11: plot_exemplary_roc
def plot_exemplary_roc(fname=None):
if (fname is not None and mpl.get_backend() == u'pgf'):
fileName, fileExtension = os.path.splitext(fname)
if (fileExtension == "pdf"):
pf.latexify()
if(fileExtension == "pgf"):
pf.latexifypgf()
frange = [0.0, 1.0]
magrange = [0.0, 1.0]
fig, ax1 = pyplot.subplots()
pf.format_axes(ax1)
colors = pf.getColorList(7)
pyplot.subplots_adjust(
left=0.125, bottom=0.125, right=0.92, top=0.9, wspace=0.2, hspace=0.3)
# add title, if given
# pyplot.title("BI measurement with denoising ");
npzfile = np.load(pf.data_dir() + 'exampleROC.npz')
fpr = npzfile['fpr']
tpr = npzfile['tpr']
mean_fpr = npzfile['mean_fpr']
pyplot.plot(fpr, tpr, color=colors[
1], linestyle='-', linewidth=1.5, label="trained classifier")
pyplot.plot(mean_fpr, mean_fpr, color=colors[5], linestyle='--', linewidth=1.5, label="random classifier")
pf.modifyLegend(pyplot.legend(loc=4))
# plot it as a log-scaled graph
# update axis ranges
ax_lim = []
ax_lim[0:4] = pyplot.axis()
# check if we were given a frequency range for the plot
if (frange != None):
ax_lim[0:2] = frange
# check if we were given a dB range for the magnitude part of the plot
# magrange = [0.2, 1.01]
if (magrange != None):
ax_lim[2:4] = magrange
pyplot.axis(ax_lim)
pyplot.grid(True)
# turn on the minor gridlines to give that awesome log-scaled look
pyplot.grid(True, which='minor')
pyplot.xlabel("False positive rate")
# pyplot.title("(b)");
pyplot.ylabel("True positive rate")
if (fname != None and mpl.get_backend() == u'pgf'):
pyplot.savefig(fname, dpi=pf.getDpi())
else:
pyplot.show()
开发者ID:holgern,项目名称:TUB_PhDThesisTemplate,代码行数:51,代码来源:plot_exemplary_roc.py
示例12: redraw
def redraw(figure):
if 'inline' in matplotlib.get_backend():
from IPython import display
display.clear_output(wait=True)
display.display(figure)
else:
plt.draw()
开发者ID:qyx268,项目名称:plato,代码行数:7,代码来源:plato_environment.py
示例13: mpl_test_settings
def mpl_test_settings(request):
from matplotlib.testing.decorators import _do_cleanup
original_units_registry = matplotlib.units.registry.copy()
original_settings = matplotlib.rcParams.copy()
backend = None
backend_marker = request.keywords.get('backend')
if backend_marker is not None:
assert len(backend_marker.args) == 1, \
"Marker 'backend' must specify 1 backend."
backend = backend_marker.args[0]
prev_backend = matplotlib.get_backend()
style = '_classic_test' # Default of cleanup and image_comparison too.
style_marker = request.keywords.get('style')
if style_marker is not None:
assert len(style_marker.args) == 1, \
"Marker 'style' must specify 1 style."
style = style_marker.args[0]
matplotlib.testing.setup()
if backend is not None:
# This import must come after setup() so it doesn't load the default
# backend prematurely.
import matplotlib.pyplot as plt
plt.switch_backend(backend)
matplotlib.style.use(style)
try:
yield
finally:
if backend is not None:
plt.switch_backend(prev_backend)
_do_cleanup(original_units_registry,
original_settings)
开发者ID:adnanb59,项目名称:matplotlib,代码行数:35,代码来源:conftest.py
示例14: software_stack
def software_stack():
"""
Import all the hard dependencies.
Returns a dict with the version.
"""
# Mandatory
import numpy, scipy
d = dict(
numpy=numpy.version.version,
scipy=scipy.version.version,
)
# Optional but strongly suggested.
try:
import netCDF4, matplotlib
d.update(dict(
netCDF4=netCDF4.getlibversion(),
matplotlib="Version: %s, backend: %s" % (matplotlib.__version__, matplotlib.get_backend()),
))
except ImportError:
pass
# Optional (GUIs).
try:
import wx
d["wx"] = wx.version()
except ImportError:
pass
return d
开发者ID:akakcolin,项目名称:abipy,代码行数:31,代码来源:abilab.py
示例15: __init__
def __init__(self, dendrogram, hub, catalog, xaxis, yaxis):
self.hub = hub
self.dendrogram = dendrogram
self.structures = list(self.dendrogram.all_structures)
self.fig = plt.figure()
self.axes = plt.subplot(1,1,1)
self.catalog = catalog
self.xdata = catalog[xaxis]
self.ydata = catalog[yaxis]
self.xys = np.column_stack((self.xdata, self.ydata))
self.x_column_name = xaxis
self.y_column_name = yaxis
self.lines2d = {} # selection_id -> matplotlib.lines.Line2D
# This is a workaround for a (likely) bug in matplotlib.widgets. Lasso crashes without this fix.
if matplotlib.get_backend() == 'MacOSX':
self.fig.canvas.supports_blit = False
self._draw_plot()
self.hub.add_callback(self.update_selection)
self.cid = self.fig.canvas.mpl_connect('button_press_event', self.onpress)
# If things are already selected in the hub, go select them!
for selection_id in self.hub.selections:
self.update_selection(selection_id)
开发者ID:dendrograms,项目名称:astrodendro,代码行数:32,代码来源:scatter.py
示例16: switch_backend
def switch_backend(backend, sloppy=True):
"""
Switch matplotlib backend.
:type backend: str
:param backend: Name of matplotlib backend to switch to.
:type sloppy: bool
:param sloppy: If ``True``, only uses
:func:`matplotlib.pyplot.switch_backend` and no warning will be
shown if the backend was not switched successfully. If ``False``,
additionally tries to use :func:`matplotlib.use` first and also
shows a warning if the backend was not switched successfully.
"""
import matplotlib
# sloppy. only do a `plt.switch_backend(..)`
if sloppy:
import matplotlib.pyplot as plt
plt.switch_backend(backend)
else:
# check if `matplotlib.use(..)` is emitting a warning
try:
with warnings.catch_warnings(record=True):
warnings.simplefilter("error", UserWarning)
matplotlib.use(backend)
# if that's the case, follow up with `plt.switch_backend(..)`
except UserWarning:
import matplotlib.pyplot as plt
plt.switch_backend(backend)
# finally check if the switch was successful,
# show a warning if not
if matplotlib.get_backend().upper() != backend.upper():
msg = "Unable to change matplotlib backend to '%s'" % backend
warnings.warn(msg)
开发者ID:adakite,项目名称:obspy,代码行数:33,代码来源:misc.py
示例17: setWindowRectangle
def setWindowRectangle(x, y=None, w=None, h=None, mngr=None, be=None):
""" Position the current Matplotlib figure at the specified position
"""
if y is None:
y = x[1]
w = x[2]
h = x[3]
x = x[0]
if mngr is None:
mngr = plt.get_current_fig_manager()
be = matplotlib.get_backend()
if be == 'WXAgg':
mngr.canvas.manager.window.SetPosition((x, y))
mngr.canvas.manager.window.SetSize((w, h))
elif be == 'agg':
# mngr.canvas.manager.window.setGeometry(x,y,w,h)
mngr.canvas.manager.window.SetPosition((x, y))
mngr.canvas.manager.window.resize(w, h)
elif be == 'module://IPython.kernel.zmq.pylab.backend_inline':
pass
else:
# assume Qt canvas
mngr.canvas.manager.window.move(x, y)
mngr.canvas.manager.window.resize(w, h)
mngr.canvas.manager.window.setGeometry(x, y, w, h)
开发者ID:eendebakpt,项目名称:oapackage,代码行数:26,代码来源:oahelper.py
示例18: check_for_modules
def check_for_modules(module_list):
# make sure module_list only contains recognized modules
unnamed_modules = set(module_list) - set(CMD_DICT.keys())
unnamed_modules = unnamed_modules - {'datetime', 're'}
if unnamed_modules:
msg = '\n\nThese modules unrecognized by check_for_modules(): '
msg += '{}\n'.format(unnamed_modules)
raise ValueError(msg)
# try using configured backend ignoring errors so they'll be caught later
if set(module_list).intersection({'matplotlib', 'pylab', 'seaborn'}):
CONFIG = config_lib.get_config()
try:
import matplotlib
if matplotlib.get_backend() != CONFIG['plot_backend']:
matplotlib.use(CONFIG['plot_backend'])
except ImportError:
pass
# initialize an error message
msg = ''
# try importing all the required mojkdules
for module in sorted(module_list):
try:
importlib.import_module(module)
except ImportError:
# add to error message for each bad module
msg = msg if msg else HEADER
msg += '-' * 60 + '\n'
msg += "Missing module '{}'. To install use: \n".format(module)
msg += " {}\n\n".format(CMD_DICT[module])
sys.stdout.write(msg + '\n')
raise
开发者ID:richwu,项目名称:pandashells,代码行数:34,代码来源:module_checker_lib.py
示例19: _acquire_externals
def _acquire_externals(self, out):
# Test and list all dependencies:
sdeps = {True: [], False: [], 'Error': []}
for dep in sorted(externals._KNOWN):
try:
sdeps[externals.exists(dep, force=False)] += [dep]
except:
sdeps['Error'] += [dep]
out.write('EXTERNALS:\n')
out.write(' Present: %s\n' % ', '.join(sdeps[True]))
out.write(' Absent: %s\n' % ', '.join(sdeps[False]))
if len(sdeps['Error']):
out.write(' Errors in determining: %s\n' % ', '.join(sdeps['Error']))
SV = ('.__version__', ) # standard versioning
out.write(' Versions of critical externals:\n')
# First the ones known to externals,
for k, v in sorted(externals.versions.iteritems()):
out.write(' %-12s: %s\n' % (k, str(v)))
try:
if externals.exists('matplotlib'):
import matplotlib
out.write(' Matplotlib backend: %s\n'
% matplotlib.get_backend())
except Exception, exc:
out.write(' Failed to determine backend of matplotlib due to "%s"'
% str(exc))
开发者ID:Anhmike,项目名称:PyMVPA,代码行数:27,代码来源:info.py
示例20: _set_mpl_backend
def _set_mpl_backend():
try:
# We are doing local imports here to avoid poluting our namespace
import matplotlib
import os
import sys
# Set the backend to a non-interactive one for unices without X
if (
os.name == "posix"
and "DISPLAY" not in os.environ
and not (sys.platform == "darwin" and matplotlib.get_backend() == "MacOSX")
):
matplotlib.use("Agg")
except ImportError:
from .._utils.testing import skip_if_running_nose
# No need to fail when running tests
skip_if_running_nose("matplotlib not installed")
raise
else:
from ..version import _import_module_with_version_check, OPTIONAL_MATPLOTLIB_MIN_VERSION
# When matplotlib was successfully imported we need to check
# that the version is greater that the minimum required one
_import_module_with_version_check("matplotlib", OPTIONAL_MATPLOTLIB_MIN_VERSION)
开发者ID:CandyPythonFlow,项目名称:nilearn,代码行数:26,代码来源:__init__.py
注:本文中的matplotlib.get_backend函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论