Python matplotlib.get_backend() Examples
The following are 30 code examples for showing how to use matplotlib.get_backend(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
matplotlib
, or try the search function
.
Example 1
Project: binGraph Author: geekscrapy File: graph.py License: GNU Affero General Public License v3.0 | 6 votes |
def args_validation(args): # # Test to see what matplotlib backend is setup backend = matplotlib.get_backend() if not backend == 'TkAgg': log.warning('{} matplotlib backend in use. This graph generation was tested with "agg", bugs may lie ahead...'.format(backend)) # # Test to see if we should use defaults if args.graphtype == 'all': args.no_zero = __no_zero__ args.width = __width__ args.no_log = __g_log__ args.no_order = __no_order__ args.colours = __colours__ try: args.colours[0] = matplotlib.colors.to_rgba(args.colours[0]) args.colours[1] = matplotlib.colors.to_rgba(args.colours[1]) except ValueError as e: raise ArgValidationEx('Error parsing --colours: {}'.format(e))
Example 2
Project: GraphicDesignPatternByPython Author: Relph1119 File: decorators.py License: MIT License | 6 votes |
def switch_backend(backend): def switch_backend_decorator(func): @functools.wraps(func) def backend_switcher(*args, **kwargs): try: prev_backend = mpl.get_backend() matplotlib.testing.setup() plt.switch_backend(backend) return func(*args, **kwargs) finally: plt.switch_backend(prev_backend) return backend_switcher return switch_backend_decorator
Example 3
Project: python3_ios Author: holzschu File: decorators.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def switch_backend(backend): def switch_backend_decorator(func): @functools.wraps(func) def backend_switcher(*args, **kwargs): try: prev_backend = mpl.get_backend() matplotlib.testing.setup() plt.switch_backend(backend) return func(*args, **kwargs) finally: plt.switch_backend(prev_backend) return backend_switcher return switch_backend_decorator
Example 4
Project: qiskit-terra Author: Qiskit File: matplotlib.py License: Apache License 2.0 | 6 votes |
def draw(self, filename=None, verbose=False): self._draw_regs() self._draw_ops(verbose) _xl = - self._style.margin[0] _xr = self._cond['xmax'] + self._style.margin[1] _yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5 _yt = self._style.margin[3] + 0.5 self.ax.set_xlim(_xl, _xr) self.ax.set_ylim(_yb, _yt) # update figure size fig_w = _xr - _xl fig_h = _yt - _yb if self._style.figwidth < 0.0: self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w) if filename: self.figure.savefig(filename, dpi=self._style.dpi, bbox_inches='tight', facecolor=self.figure.get_facecolor()) if self.return_fig: if get_backend() in ['module://ipykernel.pylab.backend_inline', 'nbAgg']: plt.close(self.figure) return self.figure
Example 5
Project: pySINDy Author: luckystarufo File: interaction.py License: MIT License | 6 votes |
def show_inline_matplotlib_plots(): """Show matplotlib plots immediately if using the inline backend. With ipywidgets 6.0, matplotlib plots don't work well with interact when using the inline backend that comes with ipykernel. Basically, the inline backend only shows the plot after the entire cell executes, which does not play well with drawing plots inside of an interact function. See https://github.com/jupyter-widgets/ipywidgets/issues/1181/ and https://github.com/ipython/ipython/issues/10376 for more details. This function displays any matplotlib plots if the backend is the inline backend. """ if 'matplotlib' not in sys.modules: # matplotlib hasn't been imported, nothing to do. return try: import matplotlib as mpl from ipykernel.pylab.backend_inline import flush_figures except ImportError: return if mpl.get_backend() == 'module://ipykernel.pylab.backend_inline': flush_figures()
Example 6
Project: Gofer-Grader Author: data-8 File: utils.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def flush_inline_matplotlib_plots(): """ Flush matplotlib plots immediately, rather than asynchronously. Basically, the inline backend only shows the plot after the entire cell executes, which means we can't easily use a contextmanager to suppress displaying it. See https://github.com/jupyter-widgets/ipywidgets/issues/1181/ and https://github.com/ipython/ipython/issues/10376 for more details. This function displays flushes any pending matplotlib plots if we are using the inline backend. Stolen from https://github.com/jupyter-widgets/ipywidgets/blob/4cc15e66d5e9e69dac8fc20d1eb1d7db825d7aa2/ipywidgets/widgets/interaction.py#L35 """ if 'matplotlib' not in sys.modules: # matplotlib hasn't been imported, nothing to do. return try: import matplotlib as mpl from ipykernel.pylab.backend_inline import flush_figures except ImportError: return if mpl.get_backend() == 'module://ipykernel.pylab.backend_inline': flush_figures()
Example 7
Project: monopsr Author: kujason File: vis_utils.py License: MIT License | 6 votes |
def move_plt_figure(fig, x, y): """Move matplotlib figure to position https://stackoverflow.com/a/37999370 Args: fig: Figure handle x: Position x y: Position y """ plt_backend = matplotlib.get_backend() if plt_backend == 'TkAgg': fig.canvas.manager.window.wm_geometry("+%d+%d" % (x, y)) elif plt_backend == 'WXAgg': fig.canvas.manager.window.SetPosition((x, y)) else: # This works for QT and GTK # You can also use window.setGeometry fig.canvas.manager.window.move(x, y)
Example 8
Project: coffeegrindsize Author: jgagneastro File: decorators.py License: MIT License | 6 votes |
def switch_backend(backend): def switch_backend_decorator(func): @functools.wraps(func) def backend_switcher(*args, **kwargs): try: prev_backend = mpl.get_backend() matplotlib.testing.setup() plt.switch_backend(backend) return func(*args, **kwargs) finally: plt.switch_backend(prev_backend) return backend_switcher return switch_backend_decorator
Example 9
Project: CogAlg Author: boris-kz File: decorators.py License: MIT License | 6 votes |
def switch_backend(backend): def switch_backend_decorator(func): @functools.wraps(func) def backend_switcher(*args, **kwargs): try: prev_backend = mpl.get_backend() matplotlib.testing.setup() plt.switch_backend(backend) return func(*args, **kwargs) finally: plt.switch_backend(prev_backend) return backend_switcher return switch_backend_decorator
Example 10
Project: Carnets Author: holzschu File: interaction.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def show_inline_matplotlib_plots(): """Show matplotlib plots immediately if using the inline backend. With ipywidgets 6.0, matplotlib plots don't work well with interact when using the inline backend that comes with ipykernel. Basically, the inline backend only shows the plot after the entire cell executes, which does not play well with drawing plots inside of an interact function. See https://github.com/jupyter-widgets/ipywidgets/issues/1181/ and https://github.com/ipython/ipython/issues/10376 for more details. This function displays any matplotlib plots if the backend is the inline backend. """ if 'matplotlib' not in sys.modules: # matplotlib hasn't been imported, nothing to do. return try: import matplotlib as mpl from ipykernel.pylab.backend_inline import flush_figures except ImportError: return if mpl.get_backend() == 'module://ipykernel.pylab.backend_inline': flush_figures()
Example 11
Project: otter-grader Author: ucbds-infra File: gofer.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def flush_inline_matplotlib_plots(): """ Flush matplotlib plots immediately, rather than asynchronously. Basically, the inline backend only shows the plot after the entire cell executes, which means we can't easily use a contextmanager to suppress displaying it. See https://github.com/jupyter-widgets/ipywidgets/issues/1181/ and https://github.com/ipython/ipython/issues/10376 for more details. This function displays flushes any pending matplotlib plots if we are using the inline backend. Stolen from https://github.com/jupyter-widgets/ipywidgets/blob/4cc15e66d5e9e69dac8fc20d1eb1d7db825d7aa2/ipywidgets/widgets/interaction.py#L35 """ if 'matplotlib' not in sys.modules: # matplotlib hasn't been imported, nothing to do. return try: import matplotlib as mpl from ipykernel.pylab.backend_inline import flush_figures except ImportError: return # except KeyError: # return if mpl.get_backend() == 'module://ipykernel.pylab.backend_inline': flush_figures()
Example 12
Project: twitter-stock-recommendation Author: alvarobartt File: decorators.py License: MIT License | 6 votes |
def switch_backend(backend): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. def switch_backend_decorator(func): @functools.wraps(func) def backend_switcher(*args, **kwargs): try: prev_backend = mpl.get_backend() matplotlib.testing.setup() plt.switch_backend(backend) result = func(*args, **kwargs) finally: plt.switch_backend(prev_backend) return result return _copy_metadata(func, backend_switcher) return switch_backend_decorator
Example 13
Project: pymoo Author: msu-coinlab File: plot.py License: Apache License 2.0 | 5 votes |
def show(self, **kwargs): self.plot_if_not_done_yet() # in a notebook the plot method need not to be called explicitly if not in_notebook() and matplotlib.get_backend() != "agg": plt.show(**kwargs) plt.close()
Example 14
Project: pmdarima Author: alkaline-ml File: matplotlib.py License: MIT License | 5 votes |
def get_compatible_pyplot(backend=None, debug=True): """Make the backend of MPL compatible. In Travis Mac distributions, python is not installed as a framework. This means that using the TkAgg backend is the best solution (so it doesn't try to use the mac OS backend by default). Parameters ---------- backend : str, optional (default="TkAgg") The backend to default to. debug : bool, optional (default=True) Whether to log the existing backend to stderr. """ import matplotlib # If the backend provided is None, just default to # what's already being used. existing_backend = matplotlib.get_backend() if backend is not None: # Can this raise?... matplotlib.use(backend) # Print out the new backend if debug: sys.stderr.write("Currently using '%s' MPL backend, " "switching to '%s' backend%s" % (existing_backend, backend, os.linesep)) # If backend is not set via env variable, but debug is elif debug: sys.stderr.write("Using '%s' MPL backend%s" % (existing_backend, os.linesep)) from matplotlib import pyplot as plt return plt
Example 15
Project: scikit-multiflow Author: scikit-multiflow File: evaluation_visualizer.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def on_new_train_step(self, sample_id, data_buffer): """ This is the listener main function, which gives it the ability to 'listen' for the caller. Whenever the EvaluationVisualiser should be aware of some new data, the caller will invoke this function, passing the new data buffer. Parameters ---------- sample_id: int The current sample id. data_buffer: EvaluationDataBuffer A buffer containing evaluation data for a single training / visualization step. Raises ------ ValueError: If an exception is raised during the draw operation. """ try: current_time = time.time() self._clear_annotations() self._update_plots(sample_id, data_buffer) # To mitigate re-drawing overhead for fast models use frame counter (default = 5 frames). # To avoid slow refresh rate in slow models use a time limit (default = 1 sec). if (self._frame_cnt == 5) or (current_time - self._last_draw_timestamp > 1): plt.subplots_adjust(right=0.72, bottom=0.22) # Adjust subplots to include metrics annotations if get_backend() == 'nbAgg': self.fig.canvas.draw() # Force draw in'notebook' backend plt.pause(1e-9) self._frame_cnt = 0 self._last_draw_timestamp = current_time else: self._frame_cnt += 1 except BaseException as exception: raise ValueError('Failed when trying to draw plot. Exception: {} | Type: {}'. format(exception, type(exception).__name__))
Example 16
Project: sphinx-gallery Author: sphinx-gallery File: scrapers.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def _import_matplotlib(): """Import matplotlib safely.""" # make sure that the Agg backend is set before importing any # matplotlib import matplotlib matplotlib.use('agg') matplotlib_backend = matplotlib.get_backend().lower() filterwarnings("ignore", category=UserWarning, message='Matplotlib is currently using agg, which is a' ' non-GUI backend, so cannot show the figure.') if matplotlib_backend != 'agg': raise ExtensionError( "Sphinx-Gallery relies on the matplotlib 'agg' backend to " "render figures and write them to files. You are " "currently using the {} backend. Sphinx-Gallery will " "terminate the build now, because changing backends is " "not well supported by matplotlib. We advise you to move " "sphinx_gallery imports before any matplotlib-dependent " "import. Moving sphinx_gallery imports at the top of " "your conf.py file should fix this issue" .format(matplotlib_backend)) import matplotlib.pyplot as plt return matplotlib, plt
Example 17
Project: neural-network-animation Author: miloharper File: test_backend_pgf.py License: MIT License | 5 votes |
def switch_backend(backend): def switch_backend_decorator(func): def backend_switcher(*args, **kwargs): try: prev_backend = mpl.get_backend() mpl.rcdefaults() plt.switch_backend(backend) result = func(*args, **kwargs) finally: plt.switch_backend(prev_backend) return result return nose.tools.make_decorator(func)(backend_switcher) return switch_backend_decorator
Example 18
Project: keras-utilities Author: cbaziotis File: ui.py License: MIT License | 5 votes |
def move_figure(f, x, y): """Move figure's upper left corner to pixel (x, y)""" backend = matplotlib.get_backend() if backend == 'TkAgg': f.canvas.manager.window.wm_geometry("+%d+%d" % (x, y)) elif backend == 'WXAgg': f.canvas.manager.window.SetPosition((x, y)) else: # This works for QT and GTK # You can also use window.setGeometry f.canvas.manager.window.move(x, y)
Example 19
Project: tick Author: X-DataInitiative File: __init__.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def _set_mpl_backend(): """Make sure that we don't get DISPLAY problems when running without X on unices Code imported from nilearn (nilearn/nilearn/plotting/__init__.py) """ # We are doing local imports here to avoid polluting 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')) or 'DISPLAY' in os.environ and os.environ['DISPLAY'] == '-1'): matplotlib.use('Agg')
Example 20
Project: GraphicDesignPatternByPython Author: Relph1119 File: conftest.py License: MIT License | 5 votes |
def mpl_test_settings(request): from matplotlib.testing.decorators import _cleanup_cm with _cleanup_cm(): 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) with warnings.catch_warnings(): warnings.simplefilter("ignore", MatplotlibDeprecationWarning) matplotlib.style.use(style) try: yield finally: if backend is not None: plt.switch_backend(prev_backend)
Example 21
Project: GraphicDesignPatternByPython Author: Relph1119 File: figure.py License: MIT License | 5 votes |
def show(self, warn=True): """ If using a GUI backend with pyplot, display the figure window. If the figure was not created using :func:`~matplotlib.pyplot.figure`, it will lack a :class:`~matplotlib.backend_bases.FigureManagerBase`, and will raise an AttributeError. Parameters ---------- warn : bool If ``True``, issue warning when called on a non-GUI backend Notes ----- For non-GUI backends, this does nothing, in which case a warning will be issued if *warn* is ``True`` (default). """ try: manager = getattr(self.canvas, 'manager') except AttributeError as err: raise AttributeError("%s\n" "Figure.show works only " "for figures managed by pyplot, normally " "created by pyplot.figure()." % err) if manager is not None: try: manager.show() return except NonGuiException: pass if warn: warnings.warn('Matplotlib is currently using %s, which is a ' 'non-GUI backend, so cannot show the figure.' % get_backend())
Example 22
Project: python3_ios Author: holzschu File: figure.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def show(self, warn=True): """ If using a GUI backend with pyplot, display the figure window. If the figure was not created using :func:`~matplotlib.pyplot.figure`, it will lack a :class:`~matplotlib.backend_bases.FigureManagerBase`, and will raise an AttributeError. Parameters ---------- warn : bool If ``True`` and we are not running headless (i.e. on Linux with an unset DISPLAY), issue warning when called on a non-GUI backend. """ try: manager = getattr(self.canvas, 'manager') except AttributeError as err: raise AttributeError("%s\n" "Figure.show works only " "for figures managed by pyplot, normally " "created by pyplot.figure()." % err) if manager is not None: try: manager.show() return except NonGuiException: pass if (backends._get_running_interactive_framework() != "headless" and warn): warnings.warn('Matplotlib is currently using %s, which is a ' 'non-GUI backend, so cannot show the figure.' % get_backend())
Example 23
Project: qiskit-terra Author: Qiskit File: bloch.py License: Apache License 2.0 | 5 votes |
def save(self, name=None, output='png', dirc=None): """Saves Bloch sphere to file of type ``format`` in directory ``dirc``. Args: name (str): Name of saved image. Must include path and format as well. i.e. '/Users/Paul/Desktop/bloch.png' This overrides the 'format' and 'dirc' arguments. output (str): Format of output image. dirc (str): Directory for output images. Defaults to current working directory. """ self.render() if dirc: if not os.path.isdir(os.getcwd() + "/" + str(dirc)): os.makedirs(os.getcwd() + "/" + str(dirc)) if name is None: if dirc: self.fig.savefig(os.getcwd() + "/" + str(dirc) + '/bloch_' + str(self.savenum) + '.' + output) else: self.fig.savefig(os.getcwd() + '/bloch_' + str(self.savenum) + '.' + output) else: self.fig.savefig(name) self.savenum += 1 if self.fig: if get_backend() in ['module://ipykernel.pylab.backend_inline', 'nbAgg']: plt.close(self.fig)
Example 24
Project: PPG Author: qiriro File: utils.py License: MIT License | 5 votes |
def set_matplotlib_backend(backend=None): import matplotlib if matplotlib.get_backend() == 'MacOSX': matplotlib.use('TkAgg') if backend: matplotlib.use(backend)
Example 25
Project: PyCINRAD Author: CyanideCN File: utils.py License: GNU General Public License v3.0 | 5 votes |
def is_inline() -> bool: return "inline" in mpl.get_backend()
Example 26
Project: plotnine Author: has2k1 File: conftest.py License: GNU General Public License v2.0 | 5 votes |
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())
Example 27
Project: scikit-hep Author: scikit-hep File: mpl_plotter.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, show_backend=False): if show_backend: import matplotlib print(matplotlib.get_backend())
Example 28
Project: ImageFusion Author: pfchai File: test_backend_pgf.py License: MIT License | 5 votes |
def switch_backend(backend): def switch_backend_decorator(func): def backend_switcher(*args, **kwargs): try: prev_backend = mpl.get_backend() mpl.rcdefaults() plt.switch_backend(backend) result = func(*args, **kwargs) finally: plt.switch_backend(prev_backend) return result return nose.tools.make_decorator(func)(backend_switcher) return switch_backend_decorator
Example 29
Project: elektronn3 Author: ELEKTRONN File: __init__.py License: MIT License | 5 votes |
def select_mpl_backend(mpl_backend): """ Set up matplotlib to use the specified backend. This needs to be run BEFORE the first import of matplotlib.pyplot! """ import os from subprocess import check_call, CalledProcessError import matplotlib if mpl_backend.lower() == 'agg': matplotlib.use('AGG') logger.info('Using the AGG backend for matplotlib. No support for X11 windows.') else: if mpl_backend.startswith('force-'): matplotlib.use(mpl_backend.partition('force-')[-1]) else: # Prevent setting of mpl qt-backend on machines without X-server before other modules import mpl. with open(os.devnull, 'w') as devnull: try: # "xset q" will always succeed to run if an X server is currently running check_call(['xset', 'q'], stdout=devnull, stderr=devnull) if mpl_backend.lower() == 'auto': pass # Backend is silently set to system default. else: matplotlib.use(mpl_backend) print('Using the {} backend for matplotlib.'.format(matplotlib.get_backend())) # Don't set backend explicitly, use system default... # if "xset q" fails, conclude that X is not running except (OSError, CalledProcessError): print('No X11 server found. Falling back to AGG backend for matplotlib.') matplotlib.use('AGG')
Example 30
Project: orbdetpy Author: ut-astria File: __init__.py License: GNU General Public License v3.0 | 5 votes |
def maximize_plot(): try: bend = get_backend().casefold() figman = plt.get_current_fig_manager() if (bend == "gtk3agg"): figman.window.maximize() except Exception as exc: pass