Exemple #1
0
def show(close=None, block=None):
    """Show all figures as SVG/PNG payloads sent to the IPython clients.

    Parameters
    ----------
    close : bool, optional
      If true, a ``plt.close('all')`` call is automatically issued after
      sending all the figures. If this is set, the figures will entirely
      removed from the internal list of figures.
    block : Not used.
      The `block` parameter is a Matplotlib experimental parameter.
      We accept it in the function signature for compatibility with other
      backends.
    """
    if close is None:
        close = InlineBackend.instance().close_figures
    try:
        for figure_manager in Gcf.get_all_fig_managers():
            display(
                figure_manager.canvas.figure,
                metadata=_fetch_figure_metadata(figure_manager.canvas.figure)
            )
    finally:
        show._to_draw = []
        # only call close('all') if any to close
        # close triggers gc.collect, which can be slow
        if close and Gcf.get_all_fig_managers():
            matplotlib.pyplot.close('all')
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()
Exemple #3
0
 def _widgetclosed( self ):
     if self.window._destroying: return
     self.window._destroying = True
     try:
         Gcf.destroy(self.num)
     except AttributeError:
         pass
 def fig_visibility_changed(self):
     """
     Make a notification in the global figure manager that
     plot visibility was changed. This method is added to this
     class so that it can be wrapped in a QAppThreadCall.
     """
     Gcf.figure_visibility_changed(self.num)
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..."
Exemple #6
0
 def _widgetclosed(self):
     if self.window._destroying:
         return
     self.window._destroying = True
     map(self.canvas.mpl_disconnect, self._cids)
     try:
         Gcf.destroy(self.num)
     except AttributeError:
         pass
Exemple #7
0
def show(mainloop=True):
    """
    Show all the figures and enter the gtk main loop
    This should be the last line of your script
    """
    for manager in Gcf.get_all_fig_managers():
        manager.window.show()
    if mainloop and gtk.main_level() == 0 and len(Gcf.get_all_fig_managers()) > 0:
        gtk.main()
    def set_window_title(self, title):
        self.window.setWindowTitle(title)
        # We need to add a call to the figure manager here to call
        # notify methods when a figure is renamed, to update our
        # plot list.
        Gcf.figure_title_changed(self.num)

        # For the workbench we also keep the label in sync, this is
        # to allow getting a handle as plt.figure('Figure Name')
        self.canvas.figure.set_label(title)
Exemple #9
0
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()
Exemple #10
0
    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 __call__(self, **kwargs):
        managers = Gcf.get_all_fig_managers()
        if not managers:
            return

        for manager in managers:
            manager.show(**kwargs)
Exemple #12
0
 def open(self, fignum):
     self.fignum = int(fignum)
     manager = Gcf.get_fig_manager(self.fignum)
     manager.add_web_socket(self)
     _, _, w, h = manager.canvas.figure.bbox.bounds
     manager.resize(w, h)
     self.on_message('{"type":"refresh"}')
def pastefig(*figs):
    """Paste one or more figures into the console workspace.

    If no arguments are given, all available figures are pasted.  If the
    argument list contains references to invalid figures, a warning is printed
    but the function continues pasting further figures.

    Parameters
    ----------
    figs : tuple
      A tuple that can contain any mixture of integers and figure objects.
    """
    if not figs:
        show(close=False)
    else:
        fig_managers = Gcf.get_all_fig_managers()
        fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers]
           + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] )

        for fig in figs:
            canvas = fig_index.get(fig)
            if canvas is None:
                print('Warning: figure %s not available.' % fig)
            else:
                send_svg_canvas(canvas)
Exemple #14
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()
def show():
    """
    For image backends - is not required
    For GUI backends - show() is usually the last line of a pylab script and
    tells the backend that it is time to draw.  In interactive mode, this may
    be a do nothing func.  See the GTK backend for an example of how to handle
    interactive versus batch mode
    """
    global plotnumber
    global lastfile
    global filename_template
    global outdir

    for manager in Gcf.get_all_fig_managers():
        # do something to display the GUI
        pass
    lastfile = filename_template % plotnumber
    outpath = os.path.join(outdir, lastfile)
    if not os.path.exists(outdir):
        raise IOError("No such directory %s " % outdir)

    if setdpi:
        matplotlib.pyplot.savefig(outpath, dpi=setdpi)
    else:
        matplotlib.pyplot.savefig(outpath)
    plotnumber = plotnumber + 1
    return plotnumber - 1
    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)
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()
Exemple #18
0
def getfigs(*fig_nums):
    """Get a list of matplotlib figures by figure numbers.

    If no arguments are given, all available figures are returned.  If the
    argument list contains references to invalid figures, a warning is printed
    but the function continues pasting further figures.

    Parameters
    ----------
    figs : tuple
        A tuple of ints giving the figure numbers of the figures to return.
    """
    from matplotlib._pylab_helpers import Gcf
    if not fig_nums:
        fig_managers = Gcf.get_all_fig_managers()
        return [fm.canvas.figure for fm in fig_managers]
    else:
        figs = []
        for num in fig_nums:
            f = Gcf.figs.get(num)
            if f is None:
                print('Warning: figure %s not available.' % num)
            else:
                figs.append(f.canvas.figure)
        return figs
Exemple #19
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()
Exemple #20
0
 def get(self, fignum, fmt):
     fignum = int(fignum)
     manager = Gcf.get_fig_manager(fignum)
     self.set_header(
         'Content-Type', mimetypes.types_map.get(fmt, 'binary'))
     buff = BytesIO()
     manager.canvas.figure.savefig(buff, format=fmt)
     self.write(buff.getvalue())
 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
Exemple #22
0
	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
Exemple #23
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
Exemple #24
0
def secureShow():
    '''Show the graphs; but don't crash if no graphs exist.'''
    from matplotlib._pylab_helpers import Gcf
    #see if there are any diagrams
    if len(Gcf.get_all_fig_managers()) == 0:
        return
    #enter mainloop
    show()
Exemple #25
0
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 get(self, fignum):
            with open(os.path.join(WebAggApplication._mpl_dirs["web_backend"], "mpl_interface.js")) as fd:
                tpl = fd.read()

            fignum = int(fignum)
            manager = Gcf.get_fig_manager(fignum)

            t = tornado.template.Template(tpl)
            self.write(t.generate(toolitems=NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas))
def show():
    """
    Show all the figures and enter the fltk mainloop

    This should be the last line of your script
    """
    for manager in Gcf.get_all_fig_managers():
        manager.show()
    Fltk.Fl.run()
Exemple #28
0
 def send_image(self):
     canvas = Gcf.get_fig_manager(self.fignum).canvas
     diff = canvas.get_diff_image()
     if self.supports_binary:
         self.write_message(diff, binary=True)
     else:
         data_uri = "data:image/png;base64,{0}".format(
             diff.encode('base64').replace('\n', ''))
         self.write_message(data_uri)
Exemple #29
0
def show():
    """
    This over-rides matplotlibs `show` function to save instead of rendering to
    the screen.
    """
    allfm = Gcf.get_all_fig_managers()
    for fcount, fm in enumerate(allfm):
        fm.canvas.figure.savefig('%s_%02i.png' %
                                 (figure_basename, fcount+1))
Exemple #30
0
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 
    """
    for manager in Gcf.get_all_fig_managers():
        # draw figure managers' views
        manager.canvas.draw()
Exemple #31
0
def draw_if_interactive():
    if matplotlib.is_interactive():
        figManager = Gcf.get_active()
        if figManager is not None:
            figManager.canvas.draw()
Exemple #32
0
 def _widgetclosed(self):
     if self.window._destroying: return
     self.window._destroying = True
     Gcf.destroy(self.num)
Exemple #33
0
def destroy_figure(ptr, figman):
    figman.window.hide()
    Fltk.Fl.wait(0)  # This is needed to make the last figure vanish.
    Gcf.destroy(figman._num)
 def closer(event):
     Gcf.destroy(num)
Exemple #35
0
def draw_if_interactive():
    if matplotlib.is_interactive():
        figmanager = Gcf.get_active()
        if figmanager is not None:
            figmanager.show()
 def destroy(event):
     canvas.mpl_disconnect(cid)
     Gcf.destroy(manager)
def show():
    for manager in Gcf.get_all_fig_managers():
        manager.show()
Exemple #38
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():
         gtk.main_quit()
 def open(self, fignum):
     self.fignum = int(fignum)
     self.manager = Gcf.get_fig_manager(self.fignum)
     self.manager.add_web_socket(self)
     if hasattr(self, 'set_nodelay'):
         self.set_nodelay(True)
Exemple #40
0
 def show(self, **kwargs):
     self.canvas.show()
     Gcf.destroy(self._num)
Exemple #41
0
 def destroy(*args):
     self.window = None
     Gcf.destroy(self)
 def trigger(self, sender, event, data=None):
     Gcf.destroy_all()
Exemple #43
0
def render_figures(code, code_path, output_dir, output_base, config,
                   context=True, function_name=None, context_reset=False,
                   close_figs=False, raises=None):
    """ Run plot code and save the hi/low res PNGs, PDF in `output_dir`

    Save the images under `output_dir` with file names derived from
    `output_base`.

    Parameters
    ----------
    code : str
        String containing code to run.
    code_path : str
        Path of file containing code.  Usually path to ``.rst`` file.
    output_dir : str
        Path to which to write output images from plots.
    output_base : str
        Prefix for filename(s) for output image(s).
    config : instance
        Sphinx configuration instance.
    context : {True, False}, optional
        If True, use persistent context (workspace) for executing code.
        Otherwise create new empty context for executing code.
    function_name : None or str, optional
        If not-empty str, name of function to execute after executing `code`.
    context_reset : {False, True}, optional
        If True, clear persistent context (workspace) for code.
    close_figs : {False, True}, optional
        If True, close all figures generated before our `code` runs.  False can
        be useful when building up a plot with several `code` blocks.
    raises : None or Exception, optional
        Exception class that code should raise, or None, for no exception.
    """
    # -- Parse format list
    default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200}
    formats = []
    plot_formats = config.nbplot_formats
    if isinstance(plot_formats, six.string_types):
        # String Sphinx < 1.3, Split on , to mimic
        # Sphinx 1.3 and later. Sphinx 1.3 always
        # returns a list.
        plot_formats = plot_formats.split(',')
    for fmt in plot_formats:
        if isinstance(fmt, six.string_types):
            if ':' in fmt:
                suffix,dpi = fmt.split(':')
                formats.append((str(suffix), int(dpi)))
            else:
                formats.append((fmt, default_dpi.get(fmt, 80)))
        elif type(fmt) in (tuple, list) and len(fmt)==2:
            formats.append((str(fmt[0]), int(fmt[1])))
        else:
            raise PlotError('invalid image format "%r" in nbplot_formats' % fmt)

    # Build the output
    ns = plot_context if context else {}

    if context_reset:
        plt.close('all')
        matplotlib.rc_file_defaults()
        matplotlib.rcParams.update(config.nbplot_rcparams)
        plot_context.clear()

    close_figs = not context or close_figs

    # Get working directory for code execution
    if setup.config.nbplot_working_directory is not None:
        workdir = _check_wd(setup.config.nbplot_working_directory)
    elif code_path is not None:
        workdir = abspath(dirname(code_path))
    else:
        workdir = None

    if close_figs:
        plt.close('all')

    run_code(code, code_path, ns, function_name, workdir=workdir,
             pre_code=setup.config.nbplot_pre_code, raises=raises)

    images = []
    fig_managers = Gcf.get_all_fig_managers()
    for j, figman in enumerate(fig_managers):
        if len(fig_managers) == 1:
            img = ImageFile(output_base, output_dir)
        else:
            img = ImageFile("%s_%02d" % (output_base, j), output_dir)
        images.append(img)
        for format, dpi in formats:
            try:
                figman.canvas.figure.savefig(img.filename(format), dpi=dpi)
            except Exception:
                raise PlotError(traceback.format_exc())
            img.formats.append(format)

    return images
Exemple #44
0
        def delayed_destroy():
            self.window.destroy()

            if self._owns_mainloop and not Gcf.get_num_fig_managers():
                self.window.quit()
Exemple #45
0
 def destroy(*args):
     Gcf.destroy(self)
Exemple #46
0
 def on_close(self):
     Gcf.get_fig_manager(self.fignum).remove_web_socket(self)
Exemple #47
0
 def close(self):
     Gcf.destroy(self.figman._num)
Exemple #48
0
 def destroy(*args):
     Gcf.destroy(num)
Exemple #49
0
 def _draw_all():
     for f_mgr in Gcf.get_all_fig_managers():
         f_mgr.canvas.draw_idle()
Exemple #50
0
def destroy_figure(ptr, figman):
    figman.window.hide()
    Gcf.destroy(figman._num)
Exemple #51
0
def show():
    allfm = Gcf.get_all_fig_managers()
    for fcount, fm in enumerate(allfm):
        fm.canvas.figure.savefig('%s_%02i.png' % (figure_basename, fcount + 1))
Exemple #52
0
def draw_if_interactive():
    if is_interactive():
        figManager = Gcf.get_active()
        if figManager is not None:
            figManager.show()
            show(block=False)
Exemple #53
0
plt.rcdefaults()
plt.rcParams["backend"] = backend


def generate(X, Y, phi):
    R = 1 - np.hypot(X, Y)
    return np.cos(2 * np.pi * X + phi) * R


fig = plt.figure()
ax = fig.add_subplot(111)

# Make the X, Y meshgrid.
xs = np.linspace(-1, 1, 50)
ys = np.linspace(-1, 1, 50)
X, Y = np.meshgrid(xs, ys)

# Begin plotting.
tstart = time.process_time()
# Keep track of plotted frames, so that FPS estimate stays reasonable even
# after a ctrl-C's.
for i, phi in enumerate(np.linspace(0, 180. / np.pi, 100)):
    if not Gcf.get_num_fig_managers():
        break
    ax.lines.clear()
    Z = generate(X, Y, phi)
    ax.plot(X.flat, Z.flat, "sk")
    plt.pause(.001)

print("Average FPS: {}".format((i + 1) / (time.process_time() - tstart)))
Exemple #54
0
 def destroy(*args): Gcf.destroy(num)
 self.window.connect("destroy", destroy)
Exemple #55
0
 def destroy(self):
     self.window.hide()
     Fltk.Fl.wait(0)  # This is needed to make the last figure vanish.
     Gcf.destroy(self._num)
Exemple #56
0
 def close(self):
     Gcf.destroy(self)
Exemple #57
0
 def close(self):
     Gcf.destroy_all()
Exemple #58
0
 def mainloop():
     managers = Gcf.get_all_fig_managers()
     if managers:
         managers[0].window.mainloop()
 def trigger(self, sender, event, data=None):
     Gcf.destroy_fig(self.figure)
Exemple #60
0
 def _window_activated(self):
     Gcf.set_active(self)