Python matplotlib.get_backend() Examples

The following are 30 code examples of matplotlib.get_backend(). 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 also want to check out all available functions/classes of the module matplotlib , or try the search function .
Example #1
Source File: decorators.py    From coffeegrindsize with MIT License 6 votes vote down vote up
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 #2
Source File: interaction.py    From pySINDy with MIT License 6 votes vote down vote up
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 #3
Source File: matplotlib.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: decorators.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #5
Source File: utils.py    From Gofer-Grader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #6
Source File: vis_utils.py    From monopsr with MIT License 6 votes vote down vote up
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 #7
Source File: decorators.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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 #8
Source File: decorators.py    From CogAlg with MIT License 6 votes vote down vote up
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
Source File: interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #10
Source File: decorators.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
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 #11
Source File: graph.py    From binGraph with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #12
Source File: gofer.py    From otter-grader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #13
Source File: canvas.py    From hiddenlayer with MIT License 5 votes vote down vote up
def __init__(self):
        self._context = None
        self.theme = DEFAULT_THEME
        self.figure = None
        self.backend = matplotlib.get_backend()
        self.drawing_calls = []
        self.theme = DEFAULT_THEME 
Example #14
Source File: plt.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def set_pos(x, y):
    mgr = plt.get_current_fig_manager()
    backend = mpl.get_backend()
    if backend == 'TkAgg':
        mgr.window.wm_geometry("+%d+%d" % (x, y))
    elif backend == 'WXAgg':
        mgr.window.SetPosition((x, y))
    else:
        # This works for QT and GTK
        # You can also use window.setGeometry
        mgr.window.move(x, y) 
Example #15
Source File: plt.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def set_pos(x, y):
    mgr = plt.get_current_fig_manager()
    backend = mpl.get_backend()
    if backend == 'TkAgg':
        mgr.window.wm_geometry("+%d+%d" % (x, y))
    elif backend == 'WXAgg':
        mgr.window.SetPosition((x, y))
    else:
        # This works for QT and GTK
        # You can also use window.setGeometry
        mgr.window.move(x, y) 
Example #16
Source File: utils.py    From PyCINRAD with GNU General Public License v3.0 5 votes vote down vote up
def is_inline() -> bool:
    return "inline" in mpl.get_backend() 
Example #17
Source File: plot.py    From pymoo with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: mpl_plotter.py    From scikit-hep with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, show_backend=False):
        if show_backend:
            import matplotlib
            print(matplotlib.get_backend()) 
Example #19
Source File: test_backend_pgf.py    From ImageFusion with MIT License 5 votes vote down vote up
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 #20
Source File: __init__.py    From elektronn3 with MIT License 5 votes vote down vote up
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 #21
Source File: plt.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def set_pos(x, y):
    mgr = plt.get_current_fig_manager()
    backend = mpl.get_backend()
    if backend == 'TkAgg':
        mgr.window.wm_geometry("+%d+%d" % (x, y))
    elif backend == 'WXAgg':
        mgr.window.SetPosition((x, y))
    else:
        # This works for QT and GTK
        # You can also use window.setGeometry
        mgr.window.move(x, y) 
Example #22
Source File: __init__.py    From orbdetpy with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #23
Source File: mplutil.py    From netharn with Apache License 2.0 5 votes vote down vote up
def aggensure():
    """
    Ensures that you are in agg mode as long as IPython is not running

    This might help prevent errors in tmux like:
        qt.qpa.screen: QXcbConnection: Could not connect to display localhost:10.0
        Could not connect to any X display.
    """
    import matplotlib as mpl
    current_backend = mpl.get_backend()
    if current_backend != 'agg':
        ipython = _current_ipython_session()
        if not ipython:
            import kwplot
            kwplot.set_mpl_backend('agg') 
Example #24
Source File: conftest.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
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) 
Example #25
Source File: conftest.py    From plotnine with GNU General Public License v2.0 5 votes vote down vote up
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 #26
Source File: figure.py    From coffeegrindsize with MIT License 5 votes vote down vote up
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 #27
Source File: Plots.py    From pyaf with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decomp_plot(df, time, signal, estimator, residue, name = None, format='png', max_length = 1000, horizon = 1) :
    assert(df.shape[0] > 0)
    assert(df.shape[1] > 0)
    assert(time in df.columns)
    assert(signal in df.columns)
    assert(estimator in df.columns)
    assert(residue in df.columns)


    import matplotlib
    # print("MATPLOTLIB_BACKEND",  matplotlib.get_backend())
    # matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    df1 = df.tail(max(max_length , 4 * horizon));
    if(name is not None):
        plt.switch_backend('Agg')
    fig, axs = plt.subplots(ncols=2, figsize=(32, 16))
    lColor = COMPONENT_COLOR;
    if(name is not None and name.endswith("Forecast")):
        lColor = FORECAST_COLOR;
    df1.plot.line(time, [signal, estimator, residue],
                  color=[SIGNAL_COLOR, lColor, RESIDUE_COLOR],
                  ax=axs[0] , grid = True, legend=False)
    add_patched_legend(axs[0] , [signal, estimator, residue])
    residues =  df1[residue].values

    import scipy.stats as scistats
    resid = residues[~np.isnan(residues)]
    scistats.probplot(resid, dist="norm", plot=axs[1])

    if(name is not None):
        plt.switch_backend('Agg')
        fig.savefig(name + '_decomp_output.' + format)
        plt.close(fig) 
Example #28
Source File: matplotlib_plot.py    From livelossplot with MIT License 5 votes vote down vote up
def _not_inline_warning(self):
        backend = matplotlib.get_backend()
        if "backend_inline" not in backend:
            warnings.warn(
                "livelossplot requires inline plots.\nYour current backend is: {}"
                "\nRun in a Jupyter environment and execute '%matplotlib inline'.".format(backend)
            ) 
Example #29
Source File: bloch.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
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 #30
Source File: matplotlib.py    From pmdarima with MIT License 5 votes vote down vote up
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