def show(block=True, layout='', open_plot=False): """ This show is typically called via pyplot.show. In general usage a script will have a sequence of figure creation followed by a pyplot.show which effectively blocks and leaves the figures open for the user. We suspect this blocking is because the mainloop thread of the GUI is not setDaemon and thus halts python termination. To simulate this we create a non daemon dummy thread and instruct the user to use Ctrl-C to finish... """ Gcf.get_active().canvas.draw() # update the current figure # open the browser with the current active figure shown... if not _test and open_plot: try: webbrowser.open_new_tab(h5m.url + "/" + str(layout)) except: logger.warning( "Failed to open figure page in your browser. Please browse to %s/%s" % (h5m.url, str(Gcf.get_active().canvas.figure.number))) if block and not _test: print "Showing figures. Hit Ctrl-C to finish script and close figures..." try: while True: time.sleep(1) except KeyboardInterrupt: print "Shutting down..."
def show(block=True, layout="", open_plot=True): """ This show is typically called via pyplot.show. In general usage a script will have a sequence of figure creation followed by a pyplot.show which effectively blocks and leaves the figures open for the user. We suspect this blocking is because the mainloop thread of the GUI is not setDaemon and thus halts python termination. To simulate this we create a non daemon dummy thread and instruct the user to use Ctrl-C to finish... """ Gcf.get_active().canvas.draw() # update the current figure # open the browser with the current active figure shown... # if not _test and open_plot: # try: # webbrowser.open_new_tab(h5m.url + "/" + str(layout)) # except: # print "Failed to open figure page in your browser. Please browse to " + h5m.url + "/" + str(Gcf.get_active().canvas.figure.number) if block and not _test: print "Showing figures. Hit Ctrl-C to finish script and close figures..." try: while True: time.sleep(1) except KeyboardInterrupt: if not _quiet: print "Shutting down..."
def __call__(self, fig=None, block=None): """ Show all figures. If *block* is not None, then it is a boolean that overrides all other factors determining whether show blocks by calling mainloop(). The other factors are: it does not block if run inside "ipython --pylab"; it does not block in interactive mode. """ if isinstance(fig, int): manager = Gcf.get_fig_manager(fig) else: manager = Gcf.get_active() if not manager: return # for manager in managers: manager.show() if block is not None: if block: self.mainloop() return else: return if not is_interactive() or get_backend() == 'WebAgg': self.mainloop()
def draw_if_interactive(): if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.canvas.show() else: debug("Error: Figure manager `Gcf.get_active()` is None")
def show(): """ Show all the figures """ for manager in Gcf.get_all_fig_managers(): manager.window.show() figManager = Gcf.get_active() if figManager != None: figManager.canvas.draw()
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()
def show(): figmanager = Gcf.get_active() if figmanager is not None: figmanager.show() else: for manager in Gcf.get_all_fig_managers(): manager.show()
def ignore(self, event): if event.inaxes != self.ax: return True elif 'zoom' in Gcf.get_active().toolbar.mode: return True elif event.name == 'pick_event': return True return False
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()
def draw_if_interactive(): """ This should be overridden in a windowing environment if drawing should be done in interactive python mode """ if is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.canvas.draw()
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 def display_interactive(*args): display(fig) #clear up figure so it isn't displayed at end of execution try: show._to_draw.remove(fig) except ValueError: pass show._draw_called = False matplotlib.pyplot.close(fig) return fig.show = display_interactive return # fig.show = lambda *a: a #display(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
def draw_if_interactive(): """ For performance reasons, we don't want to redraw the figure after each draw command. Instead, we mark the figure as invalid, so that it will be redrawn as soon as the event loop resumes via PyOS_InputHook. This function should be called after each draw event, even if matplotlib is not running interactively. """ figManager = Gcf.get_active() if figManager is not None: figManager.canvas.invalidate()
def show(block=None): """ Show the current figure block argument is ignored """ manager = Gcf.get_active() if manager is not None: return manager.show() else: return None
def _show(): from matplotlib._pylab_helpers import Gcf active_manager = Gcf.get_active() if active_manager: import console import tempfile screen_width, screen_height = console._get_screen_size() compact = screen_width < 768 dpi = 160 if not compact else 66.2 tmp = tempfile.mktemp(suffix='.png') active_manager.canvas.figure.savefig(tmp, dpi=dpi) console.show_image(tmp)
def draw_if_interactive(): try: import matplotlib from matplotlib._pylab_helpers import Gcf if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None and figManager.canvas and figManager.canvas.figure: retval = display(figManager.canvas.figure, overwrite=(not pyplot_dict["new_plot"])) pyplot_dict["new_plot"] = False return retval except Exception: pass
def show(): """ Show all the figures and enter the qt main loop This should be the last line of your script """ for manager in Gcf.get_all_fig_managers(): manager.window.show() if DEBUG: print 'Inside show' figManager = Gcf.get_active() if figManager != None: figManager.canvas.draw() if _create_qApp.qAppCreatedHere: qt.qApp.exec_loop()
def draw_if_interactive(): """ For image backends - is not required For GUI backends - this should be overriden if drawing should be done in interactive python mode """ manager = Gcf.get_active() try: manager.canvas.draw() if not ObjCInstance(manager.view).superview(): manager.view.attach() except AttributeError: show()
def awakeFromNib(self): NSApp().setDelegate_(self) self.app = NSApp() self.canvas = Gcf.get_active().canvas self.plotView.canvas = self.canvas self.canvas.plotView = self.plotView self.plotWindow.setAcceptsMouseMovedEvents_(True) self.plotWindow.makeKeyAndOrderFront_(self) self.plotWindow.setDelegate_(self)#.plotView) self.plotView.setImageFrameStyle_(NSImageFrameGroove) self.plotView.image_ = NSImage.alloc().initWithSize_((0,0)) self.plotView.setImage_(self.plotView.image_) self.plotWindow.makeFirstResponder_(self.plotView) self.plotView.windowDidResize_(self)
def savefig(self, figure=None, **kwargs): """ Saves a :class:`~matplotlib.figure.Figure` to this file as a new page. Any other keyword arguments are passed to :meth:`~matplotlib.figure.Figure.savefig`. Parameters ---------- figure : :class:`~matplotlib.figure.Figure` or int, optional Specifies what figure is saved to file. If not specified, the active figure is saved. If a :class:`~matplotlib.figure.Figure` instance is provided, this figure is saved. If an int is specified, the figure instance to save is looked up by number. """ if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figure = manager.canvas.figure try: orig_canvas = figure.canvas figure.canvas = FigureCanvasPgf(figure) width, height = figure.get_size_inches() if self._n_figures == 0: self._write_header(width, height) else: # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and # luatex<0.85; they were renamed to \pagewidth and \pageheight # on luatex>=0.85. self._file.write( br'\newpage' br'\ifdefined\pdfpagewidth\pdfpagewidth' br'\else\pagewidth\fi=%ain' br'\ifdefined\pdfpageheight\pdfpageheight' br'\else\pageheight\fi=%ain' b'%%\n' % (width, height) ) figure.savefig(self._file, format="pgf", **kwargs) self._n_figures += 1 finally: figure.canvas = orig_canvas
def _show(): from matplotlib._pylab_helpers import Gcf active_manager = Gcf.get_active() if active_manager: import sharing, tempfile, os filepath = os.path.join(tempfile.gettempdir(), 'figure.png') i = 1 while os.path.isfile(filepath): i += 1 filepath = os.path.join(tempfile.gettempdir(), 'figure ' + str(i) + '.png') active_manager.canvas.figure.savefig(filepath) sharing.quick_look(filepath)
def addFigure(cls, title=None, num=None, thisFig=None): direction = cls.kwargs.get('direction', 'top') fig = cls(cls.clsFrame, title=title, num=num, thisFig=thisFig) # set the minsize to be large enough to avoid some following assert; it # will not eliminate all as if a page is added to a notebook, the # minsize of notebook is not the max of all its children pages (check # frameplus.py). # wxpython/ext/wxWidgets/src/gtk/bitmap.cpp(539): assert ""width > 0 && # height > 0"" failed in Create(): invalid bitmap size dp.send('frame.add_panel', panel=fig, direction=direction, title=fig.GetTitle(), target=Gcf.get_active(), minsize=(75, 75)) return fig
def savefig(self, figure=None, **kwargs): if self.create_pngs: if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figh = manager.canvas.figure else: figh = figure figh.savefig(opj(self.png_folder, '%s_%d.%s' % (self.base_name, self.page_num, self.add_format)), format=self.add_format, dpi=200) self.page_num += 1 super().savefig(figure=figure, **kwargs)
class FigureManagerPythonista(FigureManagerBase): """ Wrap everything up into a window for the pylab interface For non interactive backends, the base class does all the work """ figManager = Gcf.get_active() if figManager is not None: figManager.canvas.draw() if not figManager.view.on_screen: figManager.view.present('sheet') def __del__(self): if self.view: self.view.close() del self.view del self.canvas
def show( mainloop=True ): """ Show all the figures and enter the qt main loop This should be the last line of your script """ for manager in Gcf.get_all_fig_managers(): manager.window.show() if DEBUG: print 'Inside show' figManager = Gcf.get_active() if figManager != None: figManager.canvas.draw() #if ( createQApp ): # qtapplication.setMainWidget( figManager.canvas ) if mainloop: qApp.exec_()
def savefig(self, figure=None, **kwargs): """ Save a `.Figure` to this file as a new page. Any other keyword arguments are passed to `~.Figure.savefig`. Parameters ---------- figure : `.Figure` or int, default: the active figure The figure, or index of the figure, that is saved to the file. """ if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figure = manager.canvas.figure try: orig_canvas = figure.canvas figure.canvas = FigureCanvasPgf(figure) width, height = figure.get_size_inches() if self._n_figures == 0: self._write_header(width, height) else: # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and # luatex<0.85; they were renamed to \pagewidth and \pageheight # on luatex>=0.85. self._file.write( br'\newpage' br'\ifdefined\pdfpagewidth\pdfpagewidth' br'\else\pagewidth\fi=%ain' br'\ifdefined\pdfpageheight\pdfpageheight' br'\else\pageheight\fi=%ain' b'%%\n' % (width, height) ) figure.savefig(self._file, format="pgf", **kwargs) self._n_figures += 1 finally: figure.canvas = orig_canvas
def draw_if_interactive(): """ If interactive mode is on, this allows for updating properties of the figure when each new plotting command is called. """ manager = Gcf.get_active() interactive = matplotlib.is_interactive() angular = mpl_config.get('angular') # Don't bother continuing if we aren't in interactive mode # or if there are no active figures. Also pointless to continue # in angular mode as we don't want to reshow the figure. if not interactive or angular or manager is None: return # Allow for figure to be reshown if close is false since # this function call implies that it has been updated if not mpl_config.get('close'): manager._shown = False
def show( mainloop=True ): """ Show all the figures and enter the qt main loop This should be the last line of your script """ for manager in Gcf.get_all_fig_managers(): manager.window.show() if DEBUG: print 'Inside show' figManager = Gcf.get_active() if figManager != None: figManager.canvas.draw() #if ( createQApp ): # qtapplication.setMainWidget( figManager.canvas ) if mainloop and createQApp: qt.QObject.connect( qtapplication, qt.SIGNAL( "lastWindowClosed()" ), qtapplication, qt.SLOT( "quit()" ) ) qtapplication.exec_loop()
def _show(block=None): from matplotlib._pylab_helpers import Gcf active_manager = Gcf.get_active() if active_manager: import _sharing as sharing import tempfile, os filepath = os.path.join(tempfile.gettempdir(), 'figure.png') remove_previous = (block == False) i = 1 while os.path.isfile(filepath): i += 1 filepath = os.path.join(tempfile.gettempdir(), 'figure ' + str(i) + '.png') active_manager.canvas.figure.savefig(filepath) sharing.quick_look(filepath, remove_previous)
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
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 fig = Gcf.get_active().canvas.figure # 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 show._to_draw.append(fig) show._draw_called = True
def awakeFromNib(self): # Get a reference to the active canvas NSApp().setDelegate_(self) self.app = NSApp() self.canvas = Gcf.get_active().canvas self.plotView.canvas = self.canvas self.canvas.plotView = self.plotView self.plotWindow.setAcceptsMouseMovedEvents_(True) self.plotWindow.makeKeyAndOrderFront_(self) self.plotWindow.setDelegate_(self) #.plotView) self.plotView.setImageFrameStyle_(NSImageFrameGroove) self.plotView.image_ = NSImage.alloc().initWithSize_((0, 0)) self.plotView.setImage_(self.plotView.image_) # Make imageview first responder for key events self.plotWindow.makeFirstResponder_(self.plotView) # Force the first update self.plotView.windowDidResize_(self)
def awakeFromNib(self): # Get a reference to the active canvas NSApp().setDelegate_(self) self.app = NSApp() self.canvas = Gcf.get_active().canvas self.plotView.canvas = self.canvas self.canvas.plotView = self.plotView self.plotWindow.setAcceptsMouseMovedEvents_(True) self.plotWindow.makeKeyAndOrderFront_(self) self.plotWindow.setDelegate_(self)#.plotView) self.plotView.setImageFrameStyle_(NSImageFrameGroove) self.plotView.image_ = NSImage.alloc().initWithSize_((0,0)) self.plotView.setImage_(self.plotView.image_) # Make imageview first responder for key events self.plotWindow.makeFirstResponder_(self.plotView) # Force the first update self.plotView.windowDidResize_(self)
def savefig(self, figure=None, **kwargs): """ Saves a :class:`~matplotlib.figure.Figure` to this file as a new page. Any other keyword arguments are passed to :meth:`~matplotlib.figure.Figure.savefig`. Parameters ---------- figure : :class:`~matplotlib.figure.Figure` or int, optional Specifies what figure is saved to file. If not specified, the active figure is saved. If a :class:`~matplotlib.figure.Figure` instance is provided, this figure is saved. If an int is specified, the figure instance to save is looked up by number. """ if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figure = manager.canvas.figure try: orig_canvas = figure.canvas figure.canvas = FigureCanvasPgf(figure) width, height = figure.get_size_inches() if self._n_figures == 0: self._write_header(width, height) else: self._file.write(self._build_newpage_command(width, height)) figure.savefig(self._file, format="pgf", **kwargs) self._n_figures += 1 finally: figure.canvas = orig_canvas
def draw_if_interactive(): # 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 is_interactive(): return manager = Gcf.get_active() if manager is None: return fig = manager.canvas.figure # 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: _Backend_ipympl._to_show.remove(fig) except ValueError: # ensure it only appears in the draw list once pass # Queue up the figure for drawing in next show() call _Backend_ipympl._to_show.append(fig) _Backend_ipympl._draw_called = True
def show(close=None, block=None): # # TODO: something to do when keyword block==False ? interactive = is_interactive() manager = Gcf.get_active() if manager is None: return try: display(manager.canvas) # metadata=_fetch_figure_metadata(manager.canvas.figure) # plt.figure adds an event which makes the figure in focus the # active one. 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: Gcf.figs.pop(manager.num, None) finally: if manager.canvas.figure in _Backend_ipympl._to_show: _Backend_ipympl._to_show.remove(manager.canvas.figure)
def draw_if_interactive(): if is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.show() show(block=False)
def draw_if_interactive(): if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.show()
def ignore(self, event): #if (not Gcf.get_active().toolbar.mode == '') or event.inaxes != self.ax or event.name == 'pick_event': if (not Gcf.get_active().toolbar.mode == '') or event.inaxes != self.ax : return True
def draw_if_interactive(): #print "calling draw_if_interactive with",Gcf.get_active() self._dirty.add(Gcf.get_active())