Example #1
0
    def test_mpl_non_interactive(self):
        """IPython v0.12 sometimes turns on mpl interactive. Ensure
           we catch that"""

        import matplotlib
        assert not matplotlib.is_interactive()
        gt = glue_terminal()
        assert not matplotlib.is_interactive()
Example #2
0
 def dump_match_img(qres, ibs, aid, qreq_=None, fnum=None, *args, **kwargs):
     import plottool as pt
     import matplotlib as mpl
     # Pop save kwargs from kwargs
     save_keys = ['dpi', 'figsize', 'saveax', 'fpath', 'fpath_strict', 'verbose']
     save_vals = ut.dict_take_pop(kwargs, save_keys, None)
     savekw = dict(zip(save_keys, save_vals))
     fpath = savekw.pop('fpath')
     if fpath is None and 'fpath_strict' not in savekw:
         savekw['usetitle'] = True
     was_interactive = mpl.is_interactive()
     if was_interactive:
         mpl.interactive(False)
     # Make new figure
     if fnum is None:
         fnum = pt.next_fnum()
     #fig = pt.figure(fnum=fnum, doclf=True, docla=True)
     fig = pt.plt.figure(fnum)
     fig.clf()
     # Draw Matches
     ax, xywh1, xywh2 = qres.show_matches(ibs, aid, colorbar_=False, qreq_=qreq_, fnum=fnum, **kwargs)
     if not kwargs.get('notitle', False):
         pt.set_figtitle(qres.make_smaller_title())
     # Save Figure
     # Setting fig=fig might make the dpi and figsize code not work
     img_fpath = pt.save_figure(fpath=fpath, fig=fig, **savekw)
     if was_interactive:
         mpl.interactive(was_interactive)
     pt.plt.close(fig)  # Ensure that this figure will not pop up
     #if False:
     #    ut.startfile(img_fpath)
     return img_fpath
def new_figure_manager_given_figure(num, figure):
    """
    Create a new figure manager instance for the given figure.
    """
    _focus = windowing.FocusManager()
    window = Tk.Tk()
    window.withdraw()

    if Tk.TkVersion >= 8.5:
        # put a mpl icon on the window rather than the default tk icon. Tkinter
        # doesn't allow colour icons on linux systems, but tk >=8.5 has a iconphoto
        # command which we call directly. Source:
        # http://mail.python.org/pipermail/tkinter-discuss/2006-November/000954.html
        icon_fname = os.path.join(rcParams['datapath'], 'images', 'matplotlib.gif')
        icon_img = Tk.PhotoImage(file=icon_fname)
        try:
            window.tk.call('wm', 'iconphoto', window._w, icon_img)
        except (SystemExit, KeyboardInterrupt):
            # re-raise exit type Exceptions
            raise
        except:
            # log the failure, but carry on
            verbose.report('Could not load matplotlib icon: %s' % sys.exc_info()[1])

    canvas = FigureCanvasTkAgg(figure, master=window)
    figManager = FigureManagerTkAgg(canvas, num, window)
    if matplotlib.is_interactive():
        figManager.show()
    return figManager
Example #4
0
 def __init__(self, canvas, num):
     if _debug: print 'FigureManagerGTK.%s' % fn_name()
     FigureManagerBase.__init__(self, canvas, num)
     self.window = gtk.Window()
     self.window.set_title("Figure %d" % num)
     if (window_icon):
         self.window.set_icon_from_file(window_icon)
     self.vbox = gtk.VBox()
     self.window.add(self.vbox)
     self.vbox.show()
     self.canvas.show()
     self.canvas.figure.show = lambda *args: self.window.show()
     self.vbox.pack_start(self.canvas, True, True)
     self.toolbar = self._get_toolbar(canvas)
     w = int (self.canvas.figure.bbox.width)
     h = int (self.canvas.figure.bbox.height)
     if self.toolbar is not None:
         self.toolbar.show()
         self.vbox.pack_end(self.toolbar, False, False)
         tb_w, tb_h = self.toolbar.size_request()
         h += tb_h
     self.window.set_default_size (w, h)
     def destroy(*args):
         Gcf.destroy(num)
     self.window.connect("destroy", destroy)
     self.window.connect("delete_event", destroy)
     if matplotlib.is_interactive():
         self.window.show()
     def notify_axes_change(fig):
         'this will be called whenever the current axes is changed'
         if self.toolbar is not None: self.toolbar.update()
     self.canvas.figure.add_axobserver(notify_axes_change)
     self.canvas.grab_focus()
Example #5
0
    def __init__( self, canvas, num ):
        if DEBUG: print 'FigureManagerQT.%s' % fn_name()
        FigureManagerBase.__init__( self, canvas, num )
        self.canvas = canvas
        self.window = qt.QMainWindow( None, None, qt.Qt.WDestructiveClose )
        
        self.canvas.reparent( self.window, qt.QPoint( 0, 0 ) )
        # Give the keyboard focus to the figure instead of the manager
        self.canvas.setFocusPolicy( qt.QWidget.ClickFocus )
        self.canvas.setFocus()
        self.window.setCaption( "Figure %d" % num )
        self.window.setCentralWidget( self.canvas )
        qt.QObject.connect( self.window, qt.SIGNAL( 'destroyed()' ),
                            self._widgetclosed )
        self.window._destroying = False

        if matplotlib.rcParams['toolbar'] == 'classic':
            print "Classic toolbar is not yet supported"
            #self.toolbar = NavigationToolbar( canvas, self.window )
            self.toolbar = None
        elif matplotlib.rcParams['toolbar'] == 'toolbar2':
            self.toolbar = NavigationToolbar2QT( canvas, self.window )
        else:
            self.toolbar = None

        self.window.resize( self.canvas.size() )
        
        if matplotlib.is_interactive():
            self.window.show()

        def notify_axes_change( fig ):
           # This will be called whenever the current axes is changed
           if self.toolbar != None: self.toolbar.update()
           self.canvas.figure.add_axobserver( notify_axes_change )
def draw_if_interactive():
    import matplotlib._pylab_helpers as pylab_helpers

    if is_interactive():
        manager = pylab_helpers.Gcf.get_active()
        if manager is not None:
            manager.show()
Example #7
0
    def __init__( self, canvas, num ):
        if DEBUG: print 'FigureManagerQT.%s' % fn_name()
        FigureManagerBase.__init__( self, canvas, num )
        self.canvas = canvas
        self.window = qt.QMainWindow()
        
        self.canvas.reparent( self.window, qt.QPoint( 0, 0 ) )
        # Give the keyboard focus to the figure instead of the manager
        self.canvas.grabKeyboard()
        self.window.setCaption( "Figure %d" % num )
        self.window.setCentralWidget( self.canvas )

        if matplotlib.rcParams['toolbar'] == 'classic':
            print "Classic toolbar is not yet supported"
            #self.toolbar = NavigationToolbar( canvas, self.window )
            self.toolbar = None
        elif matplotlib.rcParams['toolbar'] == 'toolbar2':
            self.toolbar = NavigationToolbar2QT( canvas, self.window )
        else:
            self.toolbar = None

        self.window.resize( self.canvas.size() )
        
        if matplotlib.is_interactive():
            self.window.show()

        def notify_axes_change( fig ):
           # This will be called whenever the current axes is changed
           if self.toolbar != None: self.toolbar.update()
           self.canvas.figure.add_axobserver( notify_axes_change )
Example #8
0
    def show(*args, block=None, **kwargs):
        if args or kwargs:
            cbook.warn_deprecated(
                "3.1", message="Passing arguments to show(), other than "
                "passing 'block' by keyword, is deprecated %(since)s, and "
                "support for it will be removed %(removal)s.")

        ## TODO: something to do when keyword block==False ?
        from matplotlib._pylab_helpers import Gcf

        managers = Gcf.get_all_fig_managers()
        if not managers:
            return

        interactive = is_interactive()

        for manager in managers:
            manager.show()

            # plt.figure adds an event which puts the figure in focus
            # in the activeQue. Disable this behaviour, as it results in
            # figures being put as the active figure after they have been
            # shown, even in non-interactive mode.
            if hasattr(manager, '_cidgcf'):
                manager.canvas.mpl_disconnect(manager._cidgcf)

            if not interactive and manager in Gcf._activeQue:
                Gcf._activeQue.remove(manager)
Example #9
0
    def _new_figure_manager(num, *args, **kwargs):
        import pymol

        if pymol._ext_gui is None:
            return new_figure_manager(num, *args, **kwargs)

        backend_tkagg.show._needmain = False

        try:
            import Tkinter as Tk
        except ImportError:
            import tkinter as Tk

        from matplotlib.figure import Figure
        from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, FigureManagerTkAgg

        FigureClass = kwargs.pop('FigureClass', Figure)
        figure = FigureClass(*args, **kwargs)

        window = Tk.Toplevel(master=pymol._ext_gui.root)

        canvas = FigureCanvasTkAgg(figure, master=window)
        figManager = FigureManagerTkAgg(canvas, num, window)
        if matplotlib.is_interactive():
            figManager.show()
        return figManager
Example #10
0
    def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)
        self.canvas = canvas
        self.window = QtGui.QMainWindow()
        self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.window.setWindowTitle("Figure %d" % num)
        image = os.path.join(matplotlib.rcParams["datapath"], "images", "matplotlib.png")
        self.window.setWindowIcon(QtGui.QIcon(image))

        # Give the keyboard focus to the figure instead of the manager
        self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.canvas.setFocus()

        QtCore.QObject.connect(self.window, QtCore.SIGNAL("destroyed()"), self._widgetclosed)
        self.window._destroying = False

        self.toolbar = self._get_toolbar(self.canvas, self.window)
        self.window.addToolBar(self.toolbar)
        QtCore.QObject.connect(self.toolbar, QtCore.SIGNAL("message"), self.window.statusBar().showMessage)

        self.window.setCentralWidget(self.canvas)

        if matplotlib.is_interactive():
            self.window.show()

        # attach a show method to the figure for pylab ease of use
        self.canvas.figure.show = lambda *args: self.window.show()

        def notify_axes_change(fig):
            # This will be called whenever the current axes is changed
            if self.toolbar != None:
                self.toolbar.update()

        self.canvas.figure.add_axobserver(notify_axes_change)
    def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)
        self.canvas = canvas

        window = MatPlotWindow(mainWin.workSpace)
        window.setup(canvas, num)
        self.window = window


        QtCore.QObject.connect(window, QtCore.SIGNAL('destroyed()'),
                            self._widgetclosed)
        window._destroying = False

        toolbar = self._get_toolbar(canvas, window)
        window.toolbar = toolbar
        self.toolbar = toolbar
        if toolbar:
           window.mainLayout.addWidget(toolbar, 0)

        window.resize(640, 480)

        if matplotlib.is_interactive():
            window.setMinimumSize(200, 200)
            window.show()

        def notify_axes_change(fig):
           # This will be called whenever the current axes is changed
           if self.toolbar != None: self.toolbar.update()
           self.canvas.figure.add_axobserver(notify_axes_change)
Example #12
0
 def __init__( self, canvas, num ):
     if DEBUG: print 'FigureManagerQT.%s' % fn_name()
     FigureManagerBase.__init__( self, canvas, num )
     self.canvas = canvas
     self.window = FigureWindow()
     self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
     self.window.setWindowTitle("Figure %d" % num)
     image = os.path.join( matplotlib.rcParams['datapath'],'images','matplotlib.png' )
     self.window.setWindowIcon(QtGui.QIcon( image ))
     self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
     self.canvas.setFocus()
     QtCore.QObject.connect( self.window, QtCore.SIGNAL( 'destroyed()' ),
                         self._widgetclosed )
     self.window._destroying = False
     self.toolbar = self._get_toolbar(self.canvas, self.window)
     self.window.addToolBar(self.toolbar)
     QtCore.QObject.connect(self.toolbar, QtCore.SIGNAL("message"),
             self.window.statusBar().showMessage)
     cs = canvas.sizeHint()
     tbs = self.toolbar.sizeHint()
     sbs = self.window.statusBar().sizeHint()
     self.window.resize(cs.width(), cs.height()+tbs.height()+sbs.height())
     self.window.setCentralWidget(self.canvas)
     if matplotlib.is_interactive():
         self.window.show()
     self.canvas.figure.show = lambda *args: self.window.show()
     def notify_axes_change( fig ):
        if self.toolbar != None: self.toolbar.update()
     self.canvas.figure.add_axobserver( notify_axes_change )
Example #13
0
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)()
Example #14
0
 def __init__( self, canvas, num ):
     if DEBUG: print 'FigureManagerQT.%s' % fn_name()
     FigureManagerBase.__init__( self, canvas, num )
     self.canvas = canvas
     self.window = qt.QMainWindow( None, None, qt.Qt.WDestructiveClose )
     self.window.closeEvent = self._widgetCloseEvent
     centralWidget = qt.QWidget( self.window )
     self.canvas.reparent( centralWidget, qt.QPoint( 0, 0 ) )
     self.canvas.setFocusPolicy( qt.QWidget.ClickFocus )
     self.canvas.setFocus()
     self.window.setCaption( "Figure %d" % num )
     self.window._destroying = False
     self.toolbar = self._get_toolbar(self.canvas, centralWidget)
     self.layout = qt.QVBoxLayout( centralWidget )
     self.layout.addWidget( self.canvas, 1 )
     if self.toolbar:
        self.layout.addWidget( self.toolbar, 0 )
     self.window.setCentralWidget( centralWidget )
     w = self.canvas.width()
     h = self.canvas.height()
     if self.toolbar:
        h += self.toolbar.height() + 4
     self.window.resize( w, h )
     if matplotlib.is_interactive():
         self.window.show()
     self.canvas.figure.show = lambda *args: self.window.show()
     def notify_axes_change( fig ):
        if self.toolbar != None: self.toolbar.update()
     self.canvas.figure.add_axobserver( notify_axes_change )
Example #15
0
    def __init__(self):

        self._draw_count = 0
        interactive = matplotlib.is_interactive()
        matplotlib.interactive(False)
        self.roi_callback = None

        self._draw_zoom_rect = None

        self.fig = Figure(facecolor=settings.BACKGROUND_COLOR)

        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self,
                                   QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)

        FigureCanvas.updateGeometry(self)
        self.manager = FigureManager(self, 0)
        matplotlib.interactive(interactive)

        self._resize_timer = QtCore.QTimer()
        self._resize_timer.setInterval(250)
        self._resize_timer.setSingleShot(True)
        self._resize_timer.timeout.connect(self._on_timeout)

        self.renderer = None
Example #16
0
    def new_figure_manager_given_figure(cls, num, figure):
        """
        Create a new figure manager instance for the given figure.
        """
        with _restore_foreground_window_at_end():
            window = tk.Tk(className="matplotlib")
            window.withdraw()

            # Put a mpl icon on the window rather than the default tk icon.
            # Tkinter doesn't allow colour icons on linux systems, but tk>=8.5
            # has a iconphoto command which we call directly. Source:
            # http://mail.python.org/pipermail/tkinter-discuss/2006-November/000954.html
            icon_fname = str(cbook._get_data_path('images/matplotlib.ppm'))
            icon_img = tk.PhotoImage(file=icon_fname, master=window)
            try:
                window.iconphoto(False, icon_img)
            except Exception as exc:
                # log the failure (due e.g. to Tk version), but carry on
                _log.info('Could not load matplotlib icon: %s', exc)

            canvas = cls.FigureCanvas(figure, master=window)
            manager = cls.FigureManager(canvas, num, window)
            if matplotlib.is_interactive():
                manager.show()
                canvas.draw_idle()
            return manager
Example #17
0
    def __init__(self):
        self._draw_count = 0
        interactive = matplotlib.is_interactive()
        matplotlib.interactive(False)
        self.roi_callback = None

        self.fig = Figure(facecolor='#ffffff')
        try:
            self.fig.set_tight_layout(True)
        except AttributeError:  # matplotlib < 1.1
            pass

        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)

        FigureCanvas.updateGeometry(self)
        self.manager = FigureManager(self, 0)
        matplotlib.interactive(interactive)

        self._resize_timer = QTimer()
        self._resize_timer.setInterval(250)
        self._resize_timer.setSingleShot(True)
        self._resize_timer.timeout.connect(self._on_timeout)

        self.renderer = None
Example #18
0
    def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)
        self.canvas = canvas
        self.window = MainWindow()
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self._widgetclosed)

        self.window.setWindowTitle("Figure %d" % num)
        image = os.path.join(matplotlib.rcParams['datapath'],
                             'images', 'matplotlib.svg')
        self.window.setWindowIcon(QtGui.QIcon(image))

        # Give the keyboard focus to the figure instead of the
        # manager; StrongFocus accepts both tab and click to focus and
        # will enable the canvas to process event w/o clicking.
        # ClickFocus only takes the focus is the window has been
        # clicked
        # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or
        # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()

        self.window._destroying = False

        self.toolmanager = self._get_toolmanager()
        self.toolbar = self._get_toolbar(self.canvas, self.window)
        self.statusbar = None

        if self.toolmanager:
            backend_tools.add_tools_to_manager(self.toolmanager)
            if self.toolbar:
                backend_tools.add_tools_to_container(self.toolbar)
                self.statusbar = StatusbarQt(self.window, self.toolmanager)

        if self.toolbar is not None:
            self.window.addToolBar(self.toolbar)
            if not self.toolmanager:
                # add text label to status bar
                statusbar_label = QtWidgets.QLabel()
                self.window.statusBar().addWidget(statusbar_label)
                self.toolbar.message.connect(statusbar_label.setText)
            tbs_height = self.toolbar.sizeHint().height()
        else:
            tbs_height = 0

        # resize the main window so it will display the canvas with the
        # requested size:
        cs = canvas.sizeHint()
        sbs = self.window.statusBar().sizeHint()
        self._status_and_tool_height = tbs_height + sbs.height()
        height = cs.height() + self._status_and_tool_height
        self.window.resize(cs.width(), height)

        self.window.setCentralWidget(self.canvas)

        if matplotlib.is_interactive():
            self.window.show()
            self.canvas.draw_idle()

        self.window.raise_()
Example #19
0
    def new_figure_manager_given_figure(cls, num, figure):
        """
        Create a new figure manager instance for the given figure.
        """
        _focus = windowing.FocusManager()
        window = Tk.Tk(className="matplotlib")
        window.withdraw()

        # Put a mpl icon on the window rather than the default tk icon.
        # Tkinter doesn't allow colour icons on linux systems, but tk>=8.5 has
        # a iconphoto command which we call directly. Source:
        # http://mail.python.org/pipermail/tkinter-discuss/2006-November/000954.html
        icon_fname = os.path.join(
            rcParams['datapath'], 'images', 'matplotlib.ppm')
        icon_img = Tk.PhotoImage(file=icon_fname)
        try:
            window.tk.call('wm', 'iconphoto', window._w, icon_img)
        except Exception as exc:
            # log the failure (due e.g. to Tk version), but carry on
            _log.info('Could not load matplotlib icon: %s', exc)

        canvas = cls.FigureCanvas(figure, master=window)
        manager = cls.FigureManager(canvas, num, window)
        if matplotlib.is_interactive():
            manager.show()
            canvas.draw_idle()
        return manager
def draw_if_interactive():
    '''Handle whether or not the backend is in interactive mode or not.
    '''
    if matplotlib.is_interactive():
        figManager = Gcf.get_active()
        if figManager:
            figManager.canvas.draw_idle()
Example #21
0
    def destroy(self, *args):
        if _debug:
            print "FigureManagerGTK.%s" % fn_name()
        self.window.destroy()

        if Gcf.get_num_fig_managers() == 0 and not matplotlib.is_interactive() and gtk.main_level() >= 1:
            gtk.main_quit()
Example #22
0
    def __init__(self, canvas, num):
        if DEBUG: print 'FigureManagerGTK.%s' % fn_name()
        FigureManagerBase.__init__(self, canvas, num)
        
        self.window = gtk.Window()
        self.window.set_title("Figure %d" % num)

        vbox = gtk.VBox()
        self.window.add(vbox)
        vbox.show()

        self.canvas.show()
        vbox.pack_start(self.canvas, True, True)

        # must be inited after the window, drawingArea and figure
        # attrs are set
        if matplotlib.rcParams['toolbar']=='classic':
            self.toolbar = NavigationToolbar (canvas, self.window)
        elif matplotlib.rcParams['toolbar']=='toolbar2':
            self.toolbar = NavigationToolbar2GTK (canvas, self.window)
        else:
            self.toolbar = None

        if self.toolbar != None:
            self.toolbar.show()
            vbox.pack_end(self.toolbar, False, False)

        def destroy(*args): Gcf.destroy(num)
        self.window.connect("destroy", destroy)
        self.window.connect("delete_event", destroy)        
        if matplotlib.is_interactive():
            self.window.show()
Example #23
0
    def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)

        self.window = Gtk.Window()
        self.window.set_wmclass("matplotlib", "Matplotlib")
        self.set_window_title("Figure %d" % num)
        try:
            self.window.set_icon_from_file(window_icon)
        except Exception:
            # Some versions of gtk throw a glib.GError but not all, so I am not
            # sure how to catch it.  I am unhappy doing a blanket catch here,
            # but am not sure what a better way is - JDH
            _log.info('Could not load matplotlib icon: %s', sys.exc_info()[1])

        self.vbox = Gtk.Box()
        self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
        self.window.add(self.vbox)
        self.vbox.show()

        self.canvas.show()

        self.vbox.pack_start(self.canvas, True, True, 0)
        # calculate size for window
        w = int(self.canvas.figure.bbox.width)
        h = int(self.canvas.figure.bbox.height)

        self.toolmanager = self._get_toolmanager()
        self.toolbar = self._get_toolbar()
        self.statusbar = None

        def add_widget(child, expand, fill, padding):
            child.show()
            self.vbox.pack_end(child, False, False, 0)
            size_request = child.size_request()
            return size_request.height

        if self.toolmanager:
            backend_tools.add_tools_to_manager(self.toolmanager)
            if self.toolbar:
                backend_tools.add_tools_to_container(self.toolbar)
                self.statusbar = StatusbarGTK3(self.toolmanager)
                h += add_widget(self.statusbar, False, False, 0)
                h += add_widget(Gtk.HSeparator(), False, False, 0)

        if self.toolbar is not None:
            self.toolbar.show()
            h += add_widget(self.toolbar, False, False, 0)

        self.window.set_default_size(w, h)

        def destroy(*args):
            Gcf.destroy(num)
        self.window.connect("destroy", destroy)
        self.window.connect("delete_event", destroy)
        if matplotlib.is_interactive():
            self.window.show()
            self.canvas.draw_idle()

        self.canvas.grab_focus()
Example #24
0
def draw_if_interactive():
    """
    Is called after every pylab drawing command
    """
    if matplotlib.is_interactive():
        figManager =  Gcf.get_active()
        if figManager is not None:
            figManager.canvas.draw_idle()
Example #25
0
 def new_figure_manager_given_figure(num, figure):
     canvas = FigureCanvasNbAgg(figure)
     manager = FigureManagerNbAgg(canvas, num)
     if is_interactive():
         manager.show()
         figure.canvas.draw_idle()
     canvas.mpl_connect('close_event', lambda event: Gcf.destroy(num))
     return manager
Example #26
0
 def destroy(self, *args):
     if Gcf.get_num_fig_managers()==0 and not matplotlib.is_interactive():
         if self.window is not None:
             self.window.quit()
     if self.window is not None:
         #self.toolbar.destroy()
         self.window.destroy()
         self.window = None
Example #27
0
    def __init__(self, canvas, num):
        if DEBUG:
            print("FigureManagerQT.%s" % fn_name())
        FigureManagerBase.__init__(self, canvas, num)
        self.canvas = canvas
        self.window = MainWindow()
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self._widgetclosed)

        self.window.setWindowTitle("Figure %d" % num)
        image = os.path.join(matplotlib.rcParams["datapath"], "images", "matplotlib.png")
        self.window.setWindowIcon(QtGui.QIcon(image))

        # Give the keyboard focus to the figure instead of the
        # manager; StrongFocus accepts both tab and click to focus and
        # will enable the canvas to process event w/o clicking.
        # ClickFocus only takes the focus is the window has been
        # clicked
        # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or
        # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()

        self.window._destroying = False

        self.toolbar = self._get_toolbar(self.canvas, self.window)
        if self.toolbar is not None:
            self.window.addToolBar(self.toolbar)
            self.toolbar.message.connect(self._show_message)
            tbs_height = self.toolbar.sizeHint().height()
        else:
            tbs_height = 0

        # add text label to status bar
        self.statusbar_label = QtWidgets.QLabel()
        self.window.statusBar().addWidget(self.statusbar_label)

        # resize the main window so it will display the canvas with the
        # requested size:
        cs = canvas.sizeHint()
        sbs = self.window.statusBar().sizeHint()
        self._status_and_tool_height = tbs_height + sbs.height()
        height = cs.height() + self._status_and_tool_height
        self.window.resize(cs.width(), height)

        self.window.setCentralWidget(self.canvas)

        if matplotlib.is_interactive():
            self.window.show()
            self.canvas.draw_idle()

        def notify_axes_change(fig):
            # This will be called whenever the current axes is changed
            if self.toolbar is not None:
                self.toolbar.update()

        self.canvas.figure.add_axobserver(notify_axes_change)
        self.window.raise_()
Example #28
0
    def __init__(self, canvas, num):
        if _debug:
            print("FigureManagerGTK.%s" % fn_name())
        FigureManagerBase.__init__(self, canvas, num)

        self.window = gtk.Window()
        self.window.set_title("Figure %d" % num)
        if window_icon:
            try:
                self.window.set_icon_from_file(window_icon)
            except:
                # some versions of gtk throw a glib.GError but not
                # all, so I am not sure how to catch it.  I am unhappy
                # diong a blanket catch here, but an not sure what a
                # better way is - JDH
                verbose.report("Could not load matplotlib icon: %s" % sys.exc_info()[1])

        self.vbox = gtk.VBox()
        self.window.add(self.vbox)
        self.vbox.show()

        self.canvas.show()

        # attach a show method to the figure  for pylab ease of use
        self.canvas.figure.show = lambda *args: self.window.show()

        self.vbox.pack_start(self.canvas, True, True)

        self.toolbar = self._get_toolbar(canvas)

        # calculate size for window
        w = int(self.canvas.figure.bbox.width)
        h = int(self.canvas.figure.bbox.height)

        if self.toolbar is not None:
            self.toolbar.show()
            self.vbox.pack_end(self.toolbar, False, False)

            tb_w, tb_h = self.toolbar.size_request()
            h += tb_h
        self.window.set_default_size(w, h)

        def destroy(*args):
            Gcf.destroy(num)

        self.window.connect("destroy", destroy)
        self.window.connect("delete_event", destroy)
        if matplotlib.is_interactive():
            self.window.show()

        def notify_axes_change(fig):
            "this will be called whenever the current axes is changed"
            if self.toolbar is not None:
                self.toolbar.update()

        self.canvas.figure.add_axobserver(notify_axes_change)

        self.canvas.grab_focus()
Example #29
0
    def __init__( self, canvas, num ):
        if DEBUG: print 'FigureManagerQT.%s' % fn_name()
        FigureManagerBase.__init__( self, canvas, num )
        self.canvas = canvas
        self.window = QtGui.QMainWindow()
        self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.window.setWindowTitle("Figure %d" % num)
        image = os.path.join( matplotlib.rcParams['datapath'],'images','matplotlib.png' )
        self.window.setWindowIcon(QtGui.QIcon( image ))

        centralWidget = QtGui.QWidget( self.window )
        self.canvas.setParent( centralWidget )

        # Give the keyboard focus to the figure instead of the manager
        self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
        self.canvas.setFocus()

        QtCore.QObject.connect( self.window, QtCore.SIGNAL( 'destroyed()' ),
                            self._widgetclosed )
        self.window._destroying = False

        self.toolbar = self._get_toolbar(self.canvas, centralWidget)

        # Use a vertical layout for the plot and the toolbar.  Set the
        # stretch to all be in the plot so the toolbar doesn't resize.
        layout = QtGui.QVBoxLayout( centralWidget )
        layout.setMargin( 0 )
        layout.addWidget( self.canvas, 1 )
        if self.toolbar:
           layout.addWidget( self.toolbar, 0 )

        self.window.setCentralWidget( centralWidget )

        # Reset the window height so the canvas will be the right
        # size.  This ALMOST works right.  The first issue is that the
        # reported toolbar height does not include the margin (so
        # we add the margin).  The second is that the total width/height
        # is slightly smaller that we actually want.  It seems like
        # the border of the window is being included in the size but
        # AFAIK there is no way to get that size.
        w = self.canvas.width()
        h = self.canvas.height()
        if self.toolbar:
           h += self.toolbar.height() + NavigationToolbar2QT.margin
        self.window.resize( w, h )

        if matplotlib.is_interactive():
            self.window.show()

        # attach a show method to the figure for pylab ease of use
        self.canvas.figure.show = lambda *args: self.window.show()

        def notify_axes_change( fig ):
           # This will be called whenever the current axes is changed
           if self.toolbar != None: self.toolbar.update()
           self.canvas.figure.add_axobserver( notify_axes_change )
Example #30
0
def new_figure_manager_given_figure(num, figure):
    """
    Create a new figure manager instance for the given figure.
    """
    frame = FigureFrameWxAgg(num, figure)
    figmgr = frame.get_figure_manager()
    if matplotlib.is_interactive():
        figmgr.frame.Show()
    return figmgr
Example #31
0
    def destroy(self, *args):
        if hasattr(self, 'toolbar') and self.toolbar is not None:
            self.toolbar.destroy()
        if hasattr(self, 'vbox'):
            self.vbox.destroy()
        if hasattr(self, 'window'):
            self.window.destroy()
        if hasattr(self, 'canvas'):
            self.canvas.destroy()
        self.__dict__.clear()   #Is this needed? Other backends don't have it.

        if Gcf.get_num_fig_managers()==0 and \
               not matplotlib.is_interactive() and \
               gtk.main_level() >= 1:
            gtk.main_quit()
Example #32
0
def connection_info():
    """
    Return a string showing the figure and connection status for the backend.

    This is intended as a diagnostic tool, and not for general use.
    """
    result = [
        '{fig} - {socket}'.format(fig=(manager.canvas.figure.get_label()
                                       or "Figure {}".format(manager.num)),
                                  socket=manager.web_sockets)
        for manager in Gcf.get_all_fig_managers()
    ]
    if not is_interactive():
        result.append('Figures pending show: {}'.format(len(Gcf._activeQue)))
    return '\n'.join(result)
Example #33
0
    def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)
        self.canvas = canvas
        self.window = FigureWindow()
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self._widgetclosed)

        self.window.setWindowTitle("Figure %d" % num)
        image = os.path.join(matplotlib.rcParams['datapath'], 'images',
                             'matplotlib.png')
        self.window.setWindowIcon(QtGui.QIcon(image))

        # Give the keyboard focus to the figure instead of the
        # manager; StrongFocus accepts both tab and click to focus and
        # will enable the canvas to process event w/o clicking.
        # ClickFocus only takes the focus is the window has been
        # clicked
        # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or
        # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()

        self.window._destroying = False

        # No toolbar in figure currently
        self.toolbar = None
        tbs_height = 0

        # resize the main window so it will display the canvas with the
        # requested size:
        cs = canvas.sizeHint()
        self._status_and_tool_height = tbs_height
        height = cs.height() + self._status_and_tool_height
        self.window.resize(cs.width(), height)

        self.window.setWidget(self.canvas)

        _on_new_figure(self.window)

        if matplotlib.is_interactive():
            self.window.show()

        def notify_axes_change(fig):
            # This will be called whenever the current axes is changed
            if self.toolbar is not None:
                self.toolbar.update()

        self.canvas.figure.add_axobserver(notify_axes_change)
Example #34
0
    def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)
        self.canvas = canvas
        self.window = MainWindow()
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self._widgetclosed)

        self.window.setWindowTitle("Figure %d" % num)
        image = str(cbook._get_data_path('images/matplotlib.svg'))
        self.window.setWindowIcon(QtGui.QIcon(image))

        # Give the keyboard focus to the figure instead of the
        # manager; StrongFocus accepts both tab and click to focus and
        # will enable the canvas to process event w/o clicking.
        # ClickFocus only takes the focus is the window has been
        # clicked
        # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or
        # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()

        self.window._destroying = False

        self.toolmanager = self._get_toolmanager()
        self.toolbar = self._get_toolbar(self.canvas, self.window)
        self.statusbar = None

        if self.toolmanager:
            backend_tools.add_tools_to_manager(self.toolmanager)
            if self.toolbar:
                backend_tools.add_tools_to_container(self.toolbar)
                self.statusbar = StatusbarQt(self.window, self.toolmanager)

        if self.toolbar is not None:
            self.window.addToolBar(self.toolbar)
            if not self.toolmanager:
                # add text label to status bar
                statusbar_label = QtWidgets.QLabel()
                self.window.statusBar().addWidget(statusbar_label)
                self.toolbar.message.connect(statusbar_label.setText)

        self.window.setCentralWidget(self.canvas)

        if matplotlib.is_interactive():
            self.window.show()
            self.canvas.draw_idle()

        self.window.raise_()
Example #35
0
    def __init__(self, canvas, num):
        if DEBUG: print 'FigureManagerGTK.%s' % fn_name()
        FigureManagerBase.__init__(self, canvas, num)

        self.window = gtk.Window()
        self.window.set_title("Figure %d" % num)

        self.vbox = gtk.VBox()
        self.window.add(self.vbox)
        self.vbox.show()

        self.canvas.show()
        self.vbox.pack_start(self.canvas, True, True)

        # must be inited after the window, drawingArea and figure
        # attrs are set
        if matplotlib.rcParams['toolbar'] == 'classic':
            self.toolbar = NavigationToolbar(canvas, self.window)
        elif matplotlib.rcParams['toolbar'] == 'toolbar2':
            self.toolbar = NavigationToolbar2GTK(canvas, self.window)
        else:
            self.toolbar = None

        # calculate size for window
        w = int(self.canvas.figure.bbox.width())
        h = int(self.canvas.figure.bbox.height())

        if self.toolbar != None:
            self.toolbar.show()
            self.vbox.pack_end(self.toolbar, False, False)

            tb_w, tb_h = self.toolbar.size_request()
            h += tb_h
        self.window.set_default_size(w, h)

        def destroy(*args):
            Gcf.destroy(num)

        self.window.connect("destroy", destroy)
        self.window.connect("delete_event", destroy)
        if matplotlib.is_interactive():
            self.window.show()

        def notify_axes_change(fig):
            'this will be called whenever the current axes is changed'
            if self.toolbar != None: self.toolbar.update()

        self.canvas.figure.add_axobserver(notify_axes_change)
Example #36
0
    def __init__(self, canvas, num):
        self.window = Gtk.Window()
        super().__init__(canvas, num)

        self.window.set_wmclass("matplotlib", "Matplotlib")
        try:
            self.window.set_icon_from_file(window_icon)
        except Exception:
            # Some versions of gtk throw a glib.GError but not all, so I am not
            # sure how to catch it.  I am unhappy doing a blanket catch here,
            # but am not sure what a better way is - JDH
            _log.info('Could not load matplotlib icon: %s', sys.exc_info()[1])

        self.vbox = Gtk.Box()
        self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
        self.window.add(self.vbox)
        self.vbox.show()

        self.canvas.show()

        self.vbox.pack_start(self.canvas, True, True, 0)
        # calculate size for window
        w = int(self.canvas.figure.bbox.width)
        h = int(self.canvas.figure.bbox.height)

        self.toolbar = self._get_toolbar()

        if self.toolmanager:
            backend_tools.add_tools_to_manager(self.toolmanager)
            if self.toolbar:
                backend_tools.add_tools_to_container(self.toolbar)

        if self.toolbar is not None:
            self.toolbar.show()
            self.vbox.pack_end(self.toolbar, False, False, 0)
            min_size, nat_size = self.toolbar.get_preferred_size()
            h += nat_size.height

        self.window.set_default_size(w, h)

        self._destroying = False
        self.window.connect("destroy", lambda *args: Gcf.destroy(self))
        self.window.connect("delete_event", lambda *args: Gcf.destroy(self))
        if mpl.is_interactive():
            self.window.show()
            self.canvas.draw_idle()

        self.canvas.grab_focus()
Example #37
0
 def new_figure_manager_given_figure(cls, num, figure):
     # Create a wx.App instance if it has not been created so far.
     wxapp = wx.GetApp()
     if wxapp is None:
         wxapp = wx.App()
         wxapp.SetExitOnFrameDelete(True)
         cbook._setup_new_guiapp()
         # Retain a reference to the app object so that it does not get
         # garbage collected.
         _BackendWx._theWxApp = wxapp
     # Attaches figure.canvas, figure.canvas.manager.
     frame = FigureFrameWx(num, figure, canvas_class=cls.FigureCanvas)
     if mpl.is_interactive():
         frame.Show()
         figure.canvas.draw_idle()
     return figure.canvas.manager
Example #38
0
    def new_figure_manager_given_figure(num, figure):
        canvas = Canvas(figure)
        if 'nbagg.transparent' in rcParams and rcParams['nbagg.transparent']:
            figure.patch.set_alpha(0)
        manager = FigureManager(canvas, num)

        if is_interactive():
            _Backend_ipympl._to_show.append(figure)
            figure.canvas.draw_idle()

        def destroy(event):
            canvas.mpl_disconnect(cid)
            Gcf.destroy(manager)

        cid = canvas.mpl_connect('close_event', destroy)
        return manager
Example #39
0
def new_figure_manager(num, *args, **kwargs):
    """
    Create a new figure manager instance
    """
    # in order to expose the Figure constructor to the pylab
    # interface we need to create the figure here
    DEBUG_MSG("new_figure_manager()", 3, None)
    backend_wx._create_wx_app()

    FigureClass = kwargs.pop('FigureClass', Figure)
    fig = FigureClass(*args, **kwargs)
    frame = FigureFrameWxAgg(num, fig)
    figmgr = frame.get_figure_manager()
    if matplotlib.is_interactive():
        figmgr.frame.Show()
    return figmgr
Example #40
0
    def set_axes_limits(self, ax=None):
        """See Basemap.set_axes_limits() for documentation.

        This function is overridden in MapCanvas as a workaround to a problem
        in Basemap.set_axes_limits() that occurs in interactive matplotlib
        mode. If matplotlib.is_interactive() is True, Basemap.set_axes_limits()
        tries to redraw the canvas by accessing the pylab figure manager.
        If the matplotlib object is embedded in a Qt application, this manager
        is not available and an exception is raised. Hence, the interactive
        mode is disabled here before the original Basemap.set_axes_limits()
        method is called. It is restored afterwards.
        """
        intact = matplotlib.is_interactive()
        matplotlib.interactive(False)
        super(MapCanvas, self).set_axes_limits(ax=ax)
        matplotlib.interactive(intact)
Example #41
0
def new_figure_manager(num, *args, **kwargs):
    """
    Create a new figure manager instance
    """
    FigureClass = kwargs.pop('FigureClass', Figure)
    figure = FigureClass(*args, **kwargs)
    window = Fltk.Fl_Double_Window(10, 10, 30, 30)
    canvas = FigureCanvasFltkAgg(figure)
    window.end()
    #Fltk.Fl.visual(Fltk.FL_DOUBLE)
    window.show()
    window.make_current()
    figManager = FigureManagerFltkAgg(canvas, num, window)
    if matplotlib.is_interactive():
        figManager.show()
    return figManager
Example #42
0
    def __init__( self, canvas, num ):
        if DEBUG: print 'FigureManagerQT.%s' % fn_name()
        FigureManagerBase.__init__( self, canvas, num )
        self.canvas = canvas
        self.window = FigureWindow()
        self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.window.setWindowTitle("Figure %d" % num)
        image = os.path.join( matplotlib.rcParams['datapath'],'images','matplotlib.png' )
        self.window.setWindowIcon(QtGui.QIcon( image ))

        # Give the keyboard focus to the figure instead of the manager
        self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
        self.canvas.setFocus()

        QtCore.QObject.connect( self.window, QtCore.SIGNAL( 'destroyed()' ),
                            self._widgetclosed )
        self.window._destroying = False

        self.toolbar = self._get_toolbar(self.canvas, self.window)
        if self.toolbar is not None:
            self.window.addToolBar(self.toolbar)
            QtCore.QObject.connect(self.toolbar, QtCore.SIGNAL("message"),
                                   self.window.statusBar().showMessage)
            tbs_height = self.toolbar.sizeHint().height()
        else:
            tbs_height = 0

        # resize the main window so it will display the canvas with the
        # requested size:
        cs = canvas.sizeHint()
        sbs = self.window.statusBar().sizeHint()
        self.window.resize(cs.width(), cs.height()+tbs_height+sbs.height())

        self.window.setCentralWidget(self.canvas)

        if matplotlib.is_interactive():
            self.window.show()

        # attach a show method to the figure for pylab ease of use
        self.canvas.figure.show = lambda *args: self.window.show()

        def notify_axes_change( fig ):
           # This will be called whenever the current axes is changed
           if self.toolbar is not None:
               self.toolbar.update()
        self.canvas.figure.add_axobserver( notify_axes_change )
Example #43
0
    def __init__(self, canvas, num):
        self.window = MainWindow()
        super().__init__(canvas, num)
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self._widgetclosed)

        if sys.platform != "darwin":
            image = str(cbook._get_data_path('images/matplotlib.svg'))
            icon = QtGui.QIcon(image)
            self.window.setWindowIcon(icon)

        self.window._destroying = False

        self.toolbar = self._get_toolbar(self.canvas, self.window)

        if self.toolmanager:
            backend_tools.add_tools_to_manager(self.toolmanager)
            if self.toolbar:
                backend_tools.add_tools_to_container(self.toolbar)

        if self.toolbar:
            self.window.addToolBar(self.toolbar)
            tbs_height = self.toolbar.sizeHint().height()
        else:
            tbs_height = 0

        # resize the main window so it will display the canvas with the
        # requested size:
        cs = canvas.sizeHint()
        cs_height = cs.height()
        height = cs_height + tbs_height
        self.window.resize(cs.width(), height)

        self.window.setCentralWidget(self.canvas)

        if mpl.is_interactive():
            self.window.show()
            self.canvas.draw_idle()

        # Give the keyboard focus to the figure instead of the manager:
        # StrongFocus accepts both tab and click to focus and will enable the
        # canvas to process event without clicking.
        # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum
        self.canvas.setFocusPolicy(_enum("QtCore.Qt.FocusPolicy").StrongFocus)
        self.canvas.setFocus()

        self.window.raise_()
Example #44
0
    def __init__(self, canvas, num):
        if _debug: print 'FigureManagerGTK.%s' % fn_name()
        FigureManagerBase.__init__(self, canvas, num)

        self.window = gtk.Window()
        self.window.set_title("Figure %d" % num)

        self.vbox = gtk.VBox()
        self.window.add(self.vbox)
        self.vbox.show()

        self.canvas.show()

        # attach a show method to the figure  for pylab ease of use
        self.canvas.figure.show = lambda *args: self.window.show()

        self.vbox.pack_start(self.canvas, True, True)

        self.toolbar = self._get_toolbar(canvas)

        # calculate size for window
        w = int(self.canvas.figure.bbox.width)
        h = int(self.canvas.figure.bbox.height)

        if self.toolbar is not None:
            self.toolbar.show()
            self.vbox.pack_end(self.toolbar, False, False)

            tb_w, tb_h = self.toolbar.size_request()
            h += tb_h
        self.window.set_default_size(w, h)

        def destroy(*args):
            Gcf.destroy(num)

        self.window.connect("destroy", destroy)
        self.window.connect("delete_event", destroy)
        if matplotlib.is_interactive():
            self.window.show()

        def notify_axes_change(fig):
            'this will be called whenever the current axes is changed'
            if self.toolbar is not None: self.toolbar.update()

        self.canvas.figure.add_axobserver(notify_axes_change)

        self.canvas.grab_focus()
Example #45
0
    def patch_matplotlib():
        # only once
        if PatchedMatplotlib._patched_original_plot is not None:
            return True
        # noinspection PyBroadException
        try:
            # we support matplotlib version 2.0.0 and above
            import matplotlib
            if int(matplotlib.__version__.split('.')[0]) < 2:
                LoggerRoot.get_base_logger().warning(
                    'matplotlib binding supports version 2.0 and above, found version {}'.format(
                        matplotlib.__version__))
                return False

            if running_remotely():
                # disable GUI backend - make headless
                sys.modules['matplotlib'].rcParams['backend'] = 'agg'
                import matplotlib.pyplot
                sys.modules['matplotlib'].pyplot.switch_backend('agg')
            import matplotlib.pyplot as plt
            from matplotlib import _pylab_helpers
            if six.PY2:
                PatchedMatplotlib._patched_original_plot = staticmethod(sys.modules['matplotlib'].pyplot.show)
                PatchedMatplotlib._patched_original_imshow = staticmethod(sys.modules['matplotlib'].pyplot.imshow)
            else:
                PatchedMatplotlib._patched_original_plot = sys.modules['matplotlib'].pyplot.show
                PatchedMatplotlib._patched_original_imshow = sys.modules['matplotlib'].pyplot.imshow
            sys.modules['matplotlib'].pyplot.show = PatchedMatplotlib.patched_show
            # sys.modules['matplotlib'].pyplot.imshow = PatchedMatplotlib.patched_imshow
            # patch plotly so we know it failed us.
            from plotly.matplotlylib import renderer
            renderer.warnings = PatchedMatplotlib._PatchWarnings()
        except Exception:
            return False

        # patch IPython matplotlib inline mode
        # noinspection PyBroadException
        try:
            if 'IPython' in sys.modules:
                from IPython import get_ipython
                ip = get_ipython()
                if ip and matplotlib.is_interactive():
                    ip.events.register('post_execute', PatchedMatplotlib.ipython_post_execute_hook)
        except Exception:
            pass

        return True
Example #46
0
    def show_results(self,
                     dataloader: DataLoader,
                     n_items: int,
                     figsize: (int, int) = None) -> plt.Figure:
        was_interactive = matplotlib.is_interactive()
        if was_interactive:
            plt.ioff()

        figure, axes = plt.subplots(n_items, 3, squeeze=False, figsize=figsize)

        with torch.no_grad():

            def loop():
                abs_item_index = 0
                for batch_index, batch in enumerate(dataloader):
                    batch_input = batch[0]
                    batch_target = batch[1]
                    if self.use_cuda:
                        batch_input = batch_input.cuda()
                    batch_prediction = torch.argmax(
                        self.model(batch_input).cpu(),
                        dim=1).type(torch.FloatTensor)

                    for item_index in range(0, batch_input.shape[0]):
                        if abs_item_index >= n_items:
                            return
                        input, target = (batch_input[item_index],
                                         batch_target[item_index])
                        prediction = batch_prediction[item_index]

                        axes[abs_item_index][0].imshow(input.cpu().permute(
                            1, 2, 0).squeeze())
                        axes[abs_item_index][0].set_title('input')
                        axes[abs_item_index][1].imshow(target.cpu())
                        axes[abs_item_index][1].set_title('target')
                        axes[abs_item_index][2].imshow(
                            prediction.cpu().squeeze())
                        axes[abs_item_index][2].set_title('prediction')

                        abs_item_index += 1

            loop()

        if was_interactive:
            plt.ion()

        return figure
        def nosql_draw2(check_func, match):
            from matplotlib.backends.backend_agg import FigureCanvas

            try:
                from matplotlib.backends.backend_agg import Figure
            except ImportError:
                from matplotlib.figure import Figure

            was_interactive = mpl.is_interactive()
            if was_interactive:
                mpl.interactive(False)
            # fnum = 32
            fig = Figure()
            canvas = FigureCanvas(fig)  # NOQA
            # fig.clf()
            ax = fig.add_subplot(1, 1, 1)
            if check_func is not None and check_func():
                return
            ax, xywh1, xywh2 = match.show(ax=ax)
            if check_func is not None and check_func():
                return
            savekw = {
                # 'dpi' : 60,
                'dpi': 80,
            }
            axes_extents = pt.extract_axes_extents(fig)
            # assert len(axes_extents) == 1, 'more than one axes'
            extent = axes_extents[0]
            with io.BytesIO() as stream:
                # This call takes 23% - 15% of the time depending on settings
                fig.savefig(stream, bbox_inches=extent, **savekw)
                stream.seek(0)
                data = np.fromstring(stream.getvalue(), dtype=np.uint8)
            if check_func is not None and check_func():
                return
            pt.plt.close(fig)
            image = cv2.imdecode(data, 1)
            thumbsize = 221
            max_dsize = (thumbsize, thumbsize)
            dsize, sx, sy = vt.resized_clamped_thumb_dims(
                vt.get_size(image), max_dsize)
            if check_func is not None and check_func():
                return
            image = vt.resize(image, dsize)
            vt.imwrite(fpath, image)
            if check_func is not None and check_func():
                return
Example #48
0
    def __init__(self, canvas, num):
        app = _create_application()
        self.window = Gtk.Window()
        app.add_window(self.window)
        super().__init__(canvas, num)

        self.window.set_wmclass("matplotlib", "Matplotlib")
        icon_ext = "png" if sys.platform == "win32" else "svg"
        self.window.set_icon_from_file(
            str(cbook._get_data_path(f"images/matplotlib.{icon_ext}")))

        self.vbox = Gtk.Box()
        self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
        self.window.add(self.vbox)
        self.vbox.show()

        self.canvas.show()

        self.vbox.pack_start(self.canvas, True, True, 0)
        # calculate size for window
        w = int(self.canvas.figure.bbox.width)
        h = int(self.canvas.figure.bbox.height)

        self.toolbar = self._get_toolbar()

        if self.toolmanager:
            backend_tools.add_tools_to_manager(self.toolmanager)
            if self.toolbar:
                backend_tools.add_tools_to_container(self.toolbar)

        if self.toolbar is not None:
            self.toolbar.show()
            self.vbox.pack_end(self.toolbar, False, False, 0)
            min_size, nat_size = self.toolbar.get_preferred_size()
            h += nat_size.height

        self.window.set_default_size(w, h)

        self._destroying = False
        self.window.connect("destroy", lambda *args: Gcf.destroy(self))
        self.window.connect("delete_event", lambda *args: Gcf.destroy(self))
        if mpl.is_interactive():
            self.window.show()
            self.canvas.draw_idle()

        self.canvas.grab_focus()
Example #49
0
def connection_info():
    """
    Return a string showing the figure and connection status for
    the backend. This is intended as a diagnostic tool, and not for general
    use.

    """
    result = []
    for manager in Gcf.get_all_fig_managers():
        fig = manager.canvas.figure
        result.append('{} - {}'.format(
            (fig.get_label() or f"Figure {manager.num}"),
            manager.web_sockets,
        ))
    if not is_interactive():
        result.append(f'Figures pending show: {len(Gcf._activeQue)}')
    return '\n'.join(result)
Example #50
0
 def refresh_raster_plot(clk):
     if matplotlib.is_interactive():
         if myopts['showlast'] is None:
             st, sn, nmax = get_plot_coords()
             line.set_xdata(st)
             line.set_ydata(sn)
             ax.set_xlim(0, amax(st))
         else:
             st, sn, nmax = get_plot_coords(
                 clk._t - float(myopts['showlast']), clk._t)
             ax.set_xlim((clk.t - myopts['showlast']) / ms,
                         clk.t / ms)
             line.set_xdata(array(st))
             line.set_ydata(sn)
         if myopts['redraw']:
             pylab.draw()
             pylab.get_current_fig_manager().canvas.flush_events()
Example #51
0
def _new_figure_manager(num, *args, **kwargs):
    # import pymol
    if pymol._ext_gui is None:
        return new_figure_manager(num, *args, **kwargs)
    backend_tkagg.show._needmain = False
    import tkinter as Tk
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, FigureManagerTkAgg
    FigureClass = kwargs.pop('FigureClass', Figure)
    print(kwargs)
    figure = FigureClass(*args, **kwargs)
    window = Tk.Toplevel(master=pymol._ext_gui.root)
    canvas = FigureCanvasTkAgg(figure, master=window)
    figManager = FigureManagerTkAgg(canvas, num, window)
    if matplotlib.is_interactive():
        figManager.show()
    return figManager
Example #52
0
def connection_info():
    """
    Return a string showing the figure and connection status for
    the backend. This is intended as a diagnostic tool, and not for general
    use.

    """
    from matplotlib._pylab_helpers import Gcf
    result = []
    for manager in Gcf.get_all_fig_managers():
        fig = manager.canvas.figure
        result.append('{0} - {1}'.format(
            (fig.get_label() or "Figure {}".format(manager.num)),
            manager.web_sockets))
    if not is_interactive():
        result.append('Figures pending show: {0}'.format(len(Gcf._activeQue)))
    return '\n'.join(result)
Example #53
0
    def make_metrics_figure(self) -> plt.Figure:
        was_interactive = matplotlib.is_interactive()
        if was_interactive:
            plt.ioff()

        figure = plt.figure(figsize=(20, 20))
        ax = figure.add_subplot()

        metrics = self.get_full_metrics_history()
        for key, values in metrics.items():
            ax.plot(list(range(0, len(values))), values, label=key)
        figure.legend()

        if was_interactive:
            plt.ion()

        return figure
Example #54
0
def ind_sc_plots(est_ret, treatment_date, unit):
    Y = est_ret.Y[unit, :]
    Y_sc_full = est_ret.get_sc(treatment_date)
    Y_sc = Y_sc_full[unit, :]
    T0 = est_ret.T0
    if est_ret.ind_CI is not None:
        ind_ci = est_ret.ind_CI[treatment_date]
    else:
        ind_ci = None
    istat = matplotlib.is_interactive()
    plt.ioff()
    sc_raw_fig, sc_raw_ax = plt.subplots(num="sc_raw")
    if ind_ci is not None:
        sc_raw_ax.fill_between(
            range(len(Y_sc)),
            Y_sc + ind_ci.ci_low,
            Y_sc + ind_ci.ci_high,
            facecolor="gray",
            label="CI",
        )
    sc_raw_ax.axvline(x=T0, linestyle="--")
    sc_raw_ax.plot(Y, "bx-", label="Unit")
    sc_raw_ax.plot(Y_sc, "gx--", label="SC")
    sc_raw_ax.set_xlabel("Time")
    sc_raw_ax.set_ylabel("Outcome")
    sc_raw_ax.legend(loc=1)

    sc_diff_fig, sc_diff_ax = plt.subplots(num="sc_diff")
    diff = Y - Y_sc
    if ind_ci is not None:
        sc_diff_ax.fill_between(
            range(len(ind_ci.ci_low)),
            diff + ind_ci.ci_low,
            diff + ind_ci.ci_high,
            facecolor="gray",
            label="CI",
        )
    sc_diff_ax.axvline(x=T0, linestyle="--")
    sc_diff_ax.axhline(y=0, linestyle="--")
    sc_diff_ax.plot(diff, "kx--", label="Unit Diff")
    sc_diff_ax.set_xlabel("Time")
    sc_diff_ax.set_ylabel("Real-SC Outcome Difference")
    sc_diff_ax.legend(loc=1)
    if istat:
        plt.ion()
    return [sc_raw_fig, sc_diff_fig]
Example #55
0
def _init_config():
    dpi = matplotlib.rcParams['figure.dpi']
    if matplotlib.__version__ < '1.2.0':
        matplotlib.rcParams.update({'savefig.format': 'png'})
    fmt = matplotlib.rcParams['savefig.format']
    width, height = matplotlib.rcParams['figure.figsize']
    fontsize = matplotlib.rcParams['font.size']
    _config['dpi'] = dpi
    _config['format'] = fmt
    _config['width'] = width*dpi
    _config['height'] = height*dpi
    _config['fontsize'] = fontsize
    _config['close'] = True
    _config['interactive'] = matplotlib.is_interactive()
    _config['angular'] = False
    _config['supported_formats'] = ['png', 'jpg', 'svg']
    _config['context'] = None
Example #56
0
    def destroy(self, *args):
        if self._destroying:
            # Otherwise, this can be called twice when the user presses 'q',
            # which calls Gcf.destroy(self), then this destroy(), then triggers
            # Gcf.destroy(self) once again via
            # `connect("destroy", lambda *args: Gcf.destroy(self))`.
            return
        self._destroying = True
        self.vbox.destroy()
        self.window.destroy()
        self.canvas.destroy()
        if self.toolbar:
            self.toolbar.destroy()

        if (Gcf.get_num_fig_managers() == 0 and not mpl.is_interactive()
                and Gtk.main_level() >= 1):
            Gtk.main_quit()
Example #57
0
def test_ioff():
    plt.ion()
    assert mpl.is_interactive()
    with plt.ioff():
        assert not mpl.is_interactive()
    assert mpl.is_interactive()

    plt.ioff()
    assert not mpl.is_interactive()
    with plt.ioff():
        assert not mpl.is_interactive()
    assert not mpl.is_interactive()
Example #58
0
def _auto_draw_if_interactive(fig, val):
    """
    An internal helper function for making sure that auto-redrawing
    works as intended in the plain python repl.

    Parameters
    ----------
    fig : Figure
        A figure object which is assumed to be associated with a canvas
    """
    if (val and is_interactive() and not fig.canvas.is_saving()
            and not fig.canvas._is_idle_drawing):
        # Some artists can mark themselves as stale in the middle of drawing
        # (e.g. axes position & tick labels being computed at draw time), but
        # this shouldn't trigger a redraw because the current redraw will
        # already take them into account.
        with fig.canvas._idle_draw_cntx():
            fig.canvas.draw_idle()
Example #59
0
    def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)
        title = "Figure %d" % num
        _macosx.FigureManager.__init__(self, canvas, title)
        if rcParams['toolbar']=='toolbar2':
            self.toolbar = NavigationToolbar2Mac(canvas)
        else:
            self.toolbar = None
        if self.toolbar is not None:
            self.toolbar.update()

        def notify_axes_change(fig):
            'this will be called whenever the current axes is changed'
            if self.toolbar != None: self.toolbar.update()
        self.canvas.figure.add_axobserver(notify_axes_change)

        if matplotlib.is_interactive():
            self.show()
Example #60
0
def draw_if_interactive():
    """
    Is called after every pylab drawing command
    """
    # signal that the current active figure should be sent at the end of
    # execution.  Also sets the _draw_called flag, signaling that there will be
    # something to send.  At the end of the code execution, a separate call to
    # flush_figures() will act upon these values
    manager = Gcf.get_active()
    if manager is None:
        return
    fig = manager.canvas.figure

    # Hack: matplotlib FigureManager objects in interacive backends (at least
    # in some of them) monkeypatch the figure object and add a .show() method
    # to it.  This applies the same monkeypatch in order to support user code
    # that might expect `.show()` to be part of the official API of figure
    # objects.
    # For further reference:
    # https://github.com/ipython/ipython/issues/1612
    # https://github.com/matplotlib/matplotlib/issues/835

    if not hasattr(fig, 'show'):
        # Queue up `fig` for display
        fig.show = lambda *a: display(fig,
                                      metadata=_fetch_figure_metadata(fig))

    # If matplotlib was manually set to non-interactive mode, this function
    # should be a no-op (otherwise we'll generate duplicate plots, since a user
    # who set ioff() manually expects to make separate draw/show calls).
    if not matplotlib.is_interactive():
        return

    # ensure current figure will be drawn, and each subsequent call
    # of draw_if_interactive() moves the active figure to ensure it is
    # drawn last
    try:
        show._to_draw.remove(fig)
    except ValueError:
        # ensure it only appears in the draw list once
        pass
    # Queue up the figure for drawing in next show() call
    show._to_draw.append(fig)
    show._draw_called = True