Python matplotlib.pylab() Examples

The following are 29 code examples for showing how to use matplotlib.pylab(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: OpenTrader   Author: OpenTrading   File: OTBackTest.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def vPlotEquityCurves(oBt, mOhlc, oChefModule,
                      sPeriod='W',
                      close_label='C',):
    import matplotlib
    import matplotlib.pylab as pylab
    # FixMe:
    matplotlib.rcParams['figure.figsize'] = (10, 5)

    # FixMe: derive the period from the sTimeFrame
    oChefModule.vPlotEquity(oBt.equity, mOhlc, sTitle="%s\nEquity" % repr(oBt),
                            sPeriod=sPeriod,
                            close_label=close_label,
                            )
    pylab.show()

    oBt.vPlotTrades()
    pylab.legend(loc='lower left')
    pylab.show()

    ## oBt.vPlotTrades(subset=slice(sYear+'-05-01', sYear+'-09-01'))
    ## pylab.legend(loc='lower left')
    ## pylab.show() 
Example 2
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: MIT License 6 votes vote down vote up
def show(*args, **kw):
    """
    Display a figure.

    When running in ipython with its pylab mode, display all
    figures and return to the ipython prompt.

    In non-interactive mode, display all figures and block until
    the figures have been closed; in interactive mode it has no
    effect unless figures were created prior to a change from
    non-interactive to interactive mode (not recommended).  In
    that case it displays the figures but does not block.

    A single experimental keyword argument, *block*, may be
    set to True or False to override the blocking behavior
    described above.
    """
    global _show
    _show(*args, **kw) 
Example 3
Project: Computable   Author: ktraunmueller   File: pylabtools.py    License: MIT License 6 votes vote down vote up
def activate_matplotlib(backend):
    """Activate the given backend and set interactive to True."""

    import matplotlib
    matplotlib.interactive(True)
    
    # Matplotlib had a bug where even switch_backend could not force
    # the rcParam to update. This needs to be set *before* the module
    # magic of switch_backend().
    matplotlib.rcParams['backend'] = backend

    import matplotlib.pyplot
    matplotlib.pyplot.switch_backend(backend)

    # This must be imported last in the matplotlib series, after
    # backend/interactivity choices have been made
    import matplotlib.pylab as pylab

    pylab.show._needmain = False
    # We need to detect at runtime whether show() is called by the user.
    # For this, we wrap it into a decorator which adds a 'called' flag.
    pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) 
Example 4
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: pyplot.py    License: MIT License 6 votes vote down vote up
def show(*args, **kw):
    """
    Display a figure.

    When running in ipython with its pylab mode, display all
    figures and return to the ipython prompt.

    In non-interactive mode, display all figures and block until
    the figures have been closed; in interactive mode it has no
    effect unless figures were created prior to a change from
    non-interactive to interactive mode (not recommended).  In
    that case it displays the figures but does not block.

    A single experimental keyword argument, *block*, may be
    set to True or False to override the blocking behavior
    described above.
    """
    global _show
    _show(*args, **kw) 
Example 5
Project: neural-network-animation   Author: miloharper   File: pyplot.py    License: MIT License 6 votes vote down vote up
def show(*args, **kw):
    """
    Display a figure.
    When running in ipython with its pylab mode, display all
    figures and return to the ipython prompt.

    In non-interactive mode, display all figures and block until
    the figures have been closed; in interactive mode it has no
    effect unless figures were created prior to a change from
    non-interactive to interactive mode (not recommended).  In
    that case it displays the figures but does not block.

    A single experimental keyword argument, *block*, may be
    set to True or False to override the blocking behavior
    described above.
    """
    global _show
    return _show(*args, **kw) 
Example 6
Project: tensorflow-ffmpeg   Author: victorcampos7   File: usage_example.py    License: MIT License 6 votes vote down vote up
def _show_video(video, fps=10):
    # Import matplotlib/pylab only if needed
    import matplotlib
    matplotlib.use('TkAgg')
    import matplotlib.pylab as pl
    pl.style.use('ggplot')
    pl.axis('off')

    if fps < 0:
        fps = 25
    video /= 255.  # Pylab works in [0, 1] range
    img = None
    pause_length = 1. / fps
    try:
        for f in range(video.shape[0]):
            im = video[f, :, :, :]
            if img is None:
                img = pl.imshow(im)
            else:
                img.set_data(im)
            pl.pause(pause_length)
            pl.draw()
    except:
        pass 
Example 7
Project: gemBS   Author: heathsc   File: reportStats.py    License: GNU General Public License v3.0 6 votes vote down vote up
def drawMapqHistogram(self):
        """ From matplot lib plots a Mappping qualty histogram
        """
        #1. PLOT BUILDING
        readsMapq = self.mapping_stats.mapping_quality_reads
       
        mapqList = list(range(len(readsMapq)))
     
        matplotlib.pyplot.ioff()
        figure = plt.figure()
        plt.bar(mapqList,readsMapq,width=1,align='center',facecolor='blue', alpha=0.75)
        plt.xlabel('MapQ')
        plt.ylabel('Fragments')
        plt.title('MapQ Histogram')
        plt.axis([0, 60,min(readsMapq), max(readsMapq)])
        plt.grid(True)
        
        pylab.savefig(self.png_mapq_histogram)
        
        plt.close(figure) 
Example 8
Project: trains   Author: allegroai   File: matplotlib_bind.py    License: Apache License 2.0 6 votes vote down vote up
def update_current_task(task):
        # make sure we have a default vale
        if PatchedMatplotlib._global_image_counter_limit is None:
            from ..config import config
            PatchedMatplotlib._global_image_counter_limit = config.get('metric.matplotlib_untitled_history_size', 100)

        # if we already patched it, just update the current task
        if PatchedMatplotlib._patched_original_plot is not None:
            PatchedMatplotlib._current_task = task
        # if matplotlib is not loaded yet, get a callback hook
        elif not running_remotely() and \
                ('matplotlib.pyplot' not in sys.modules and 'matplotlib.pylab' not in sys.modules):
            PatchedMatplotlib._current_task = task
            PostImportHookPatching.add_on_import('matplotlib.pyplot', PatchedMatplotlib.patch_matplotlib)
            PostImportHookPatching.add_on_import('matplotlib.pylab', PatchedMatplotlib.patch_matplotlib)
        elif PatchedMatplotlib.patch_matplotlib():
            PatchedMatplotlib._current_task = task 
Example 9
Project: convis   Author: jahuth   File: variable_describe.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _plot_to_string():
    try:
        from StringIO import StringIO
        make_bytes = lambda x: x.buf
    except ImportError:
        from io import BytesIO as StringIO
        make_bytes = lambda x: x.getbuffer()
    try:
        from urllib import quote
    except:
        from urllib.parse import quote
    import base64
    import matplotlib.pylab as plt
    imgdata = StringIO()
    plt.savefig(imgdata)
    plt.close()
    imgdata.seek(0) 
    image = base64.encodestring(make_bytes(imgdata))
    return str(quote(image)) 
Example 10
Project: Computable   Author: ktraunmueller   File: backend_wx.py    License: MIT License 5 votes vote down vote up
def _onEnter(self, evt):
        """Mouse has entered the window."""
        FigureCanvasBase.enter_notify_event(self, guiEvent = evt)


########################################################################
#
# The following functions and classes are for pylab compatibility
# mode (matplotlib.pylab) and implement figure managers, etc...
#
######################################################################## 
Example 11
Project: Computable   Author: ktraunmueller   File: backend_wx.py    License: MIT License 5 votes vote down vote up
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)
    _create_wx_app()

    FigureClass = kwargs.pop('FigureClass', Figure)
    fig = FigureClass(*args, **kwargs)
    return new_figure_manager_given_figure(num, fig) 
Example 12
Project: Computable   Author: ktraunmueller   File: pylabtools.py    License: MIT License 5 votes vote down vote up
def mpl_runner(safe_execfile):
    """Factory to return a matplotlib-enabled runner for %run.

    Parameters
    ----------
    safe_execfile : function
      This must be a function with the same interface as the
      :meth:`safe_execfile` method of IPython.

    Returns
    -------
    A function suitable for use as the ``runner`` argument of the %run magic
    function.
    """
    
    def mpl_execfile(fname,*where,**kw):
        """matplotlib-aware wrapper around safe_execfile.

        Its interface is identical to that of the :func:`execfile` builtin.

        This is ultimately a call to execfile(), but wrapped in safeties to
        properly handle interactive rendering."""

        import matplotlib
        import matplotlib.pylab as pylab

        #print '*** Matplotlib runner ***' # dbg
        # turn off rendering until end of script
        is_interactive = matplotlib.rcParams['interactive']
        matplotlib.interactive(False)
        safe_execfile(fname,*where,**kw)
        matplotlib.interactive(is_interactive)
        # make rendering call now, if the user tried to do it
        if pylab.draw_if_interactive.called:
            pylab.draw()
            pylab.draw_if_interactive.called = False

    return mpl_execfile 
Example 13
Project: Computable   Author: ktraunmueller   File: pylabtools.py    License: MIT License 5 votes vote down vote up
def select_figure_format(shell, fmt):
    """Select figure format for inline backend, can be 'png', 'retina', or 'svg'.

    Using this method ensures only one figure format is active at a time.
    """
    from matplotlib.figure import Figure
    from IPython.kernel.zmq.pylab import backend_inline

    svg_formatter = shell.display_formatter.formatters['image/svg+xml']
    png_formatter = shell.display_formatter.formatters['image/png']

    if fmt == 'png':
        svg_formatter.type_printers.pop(Figure, None)
        png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png'))
    elif fmt in ('png2x', 'retina'):
        svg_formatter.type_printers.pop(Figure, None)
        png_formatter.for_type(Figure, retina_figure)
    elif fmt == 'svg':
        png_formatter.type_printers.pop(Figure, None)
        svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg'))
    else:
        raise ValueError("supported formats are: 'png', 'retina', 'svg', not %r" % fmt)

    # set the format to be used in the backend()
    backend_inline._figure_format = fmt

#-----------------------------------------------------------------------------
# Code for initializing matplotlib and importing pylab
#----------------------------------------------------------------------------- 
Example 14
Project: Computable   Author: ktraunmueller   File: pylabtools.py    License: MIT License 5 votes vote down vote up
def import_pylab(user_ns, import_all=True):
    """Populate the namespace with pylab-related values.
    
    Imports matplotlib, pylab, numpy, and everything from pylab and numpy.
    
    Also imports a few names from IPython (figsize, display, getfigs)
    
    """

    # Import numpy as np/pyplot as plt are conventions we're trying to
    # somewhat standardize on.  Making them available to users by default
    # will greatly help this.
    s = ("import numpy\n"
          "import matplotlib\n"
          "from matplotlib import pylab, mlab, pyplot\n"
          "np = numpy\n"
          "plt = pyplot\n"
          )
    exec s in user_ns
    
    if import_all:
        s = ("from matplotlib.pylab import *\n"
             "from numpy import *\n")
        exec s in user_ns
    
    # IPython symbols to add
    user_ns['figsize'] = figsize
    from IPython.core.display import display
    # Add display and getfigs to the user's namespace
    user_ns['display'] = display
    user_ns['getfigs'] = getfigs 
Example 15
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_wx.py    License: MIT License 5 votes vote down vote up
def _onEnter(self, evt):
        """Mouse has entered the window."""
        FigureCanvasBase.enter_notify_event(self, guiEvent = evt)


########################################################################
#
# The following functions and classes are for pylab compatibility
# mode (matplotlib.pylab) and implement figure managers, etc...
#
######################################################################## 
Example 16
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_wx.py    License: MIT License 5 votes vote down vote up
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)
    _create_wx_app()

    FigureClass = kwargs.pop('FigureClass', Figure)
    fig = FigureClass(*args, **kwargs)
    return new_figure_manager_given_figure(num, fig) 
Example 17
Project: neural-network-animation   Author: miloharper   File: backend_wx.py    License: MIT License 5 votes vote down vote up
def _onEnter(self, evt):
        """Mouse has entered the window."""
        FigureCanvasBase.enter_notify_event(self, guiEvent = evt)


########################################################################
#
# The following functions and classes are for pylab compatibility
# mode (matplotlib.pylab) and implement figure managers, etc...
#
######################################################################## 
Example 18
Project: neural-network-animation   Author: miloharper   File: backend_wx.py    License: MIT License 5 votes vote down vote up
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)
    _create_wx_app()

    FigureClass = kwargs.pop('FigureClass', Figure)
    fig = FigureClass(*args, **kwargs)
    return new_figure_manager_given_figure(num, fig) 
Example 19
Project: ImageFusion   Author: pfchai   File: backend_wx.py    License: MIT License 5 votes vote down vote up
def _onEnter(self, evt):
        """Mouse has entered the window."""
        FigureCanvasBase.enter_notify_event(self, guiEvent = evt)


########################################################################
#
# The following functions and classes are for pylab compatibility
# mode (matplotlib.pylab) and implement figure managers, etc...
#
######################################################################## 
Example 20
Project: ImageFusion   Author: pfchai   File: backend_wx.py    License: MIT License 5 votes vote down vote up
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)
    _create_wx_app()

    FigureClass = kwargs.pop('FigureClass', Figure)
    fig = FigureClass(*args, **kwargs)
    return new_figure_manager_given_figure(num, fig) 
Example 21
Project: gemBS   Author: heathsc   File: bsCallStats.py    License: GNU General Public License v3.0 5 votes vote down vote up
def saveAndClose(self):
        """Save the figure and close it"""
        pylab.savefig(self.pngFile)
        plt.close(self.figure) 
Example 22
Project: gemBS   Author: heathsc   File: reportStats.py    License: GNU General Public License v3.0 5 votes vote down vote up
def drawInsertSizePlot(self):
        """ From matplot lib plots a Insert Size Plot
        """
        iSizeList = []
        readsList = []
        
        #1. PLOT BUILDING
        histogram_template_len = self.mapping_stats.read_insert_size_histogram
        
        for insert_size_length,reads in histogram_template_len.items():
            iSizeList.append(int(insert_size_length))
            readsList.append(int(reads))
            
        matplotlib.pyplot.ioff()            
        figure = plt.figure()

        plt.plot(iSizeList, readsList, '.',color="r")
        plt.xlabel('Insert Size (bp)')
        plt.ylabel('Reads')
        plt.title('Insert Size Histogram')
        plt.axis([min(iSizeList), 800,min(readsList), max(readsList)])
        plt.grid(True)
        
        pylab.savefig(self.png_insert_size_histogram)
        
        plt.close(figure) 
Example 23
Project: gemBS   Author: heathsc   File: reportStats.py    License: GNU General Public License v3.0 5 votes vote down vote up
def drawMultipleInsertSizePlot(self):
        """ From matplot lib plots a Insert Size Plot
        """ 
        iSizeList = []
        readsList = []
        readsYaxis = []
        sizeXaxis = []
        lanesNames = []
        
        #1. PLOT BUILDING
        for laneStats in self.mapping_stats.list_lane_stats:
            lanesNames.append(laneStats.name)
            histogram_template_len = laneStats.read_insert_size_histogram
            sizeList  = []
            readList = []
            for insert_size_length,reads in histogram_template_len.items():
                sizeList.append(int(insert_size_length))
                readList.append(int(reads))
                
            readsYaxis.extend(readList)
            sizeXaxis.extend(sizeList)
            iSizeList.append(sizeList)
            readsList.append(readList)
            
        matplotlib.pyplot.ioff()            
        figure = plt.figure()

        for iSize, readList in zip(iSizeList, readsList):        
            plt.plot(iSize, readList,'.')
        
        plt.xlabel('Insert Size (bp)')
        plt.ylabel('Reads')
        plt.title('Insert Size Histogram Per Lane')
        plt.axis([min(sizeXaxis), 800,min(readsYaxis), max(readsYaxis)])
        plt.legend(lanesNames,loc='upper right')        
        
        plt.grid(True)
       
        pylab.savefig(self.png_insert_size_histogram)
        
        plt.close(figure) 
Example 24
Project: gemBS   Author: heathsc   File: reportStats.py    License: GNU General Public License v3.0 5 votes vote down vote up
def drawMultipleMapqHistogram(self):
        """ From matplot lib plots a Mappping qualty histogram
        """  
        mapqFragmentsLanes = []
              
        for laneStats in self.mapping_stats.list_lane_stats:
            mapqFragmentsLanes.append(laneStats.mapping_quality_reads)
    
        matplotlib.pyplot.ioff()
        figure = plt.figure()
        ax = figure.add_subplot(111,projection='3d')
                       
        lane = 0
        for fragmentsQuality in mapqFragmentsLanes:
            qualityRange = list(range(len(fragmentsQuality)))            
            ax.bar(qualityRange,fragmentsQuality, zs=lane, zdir='y', color='b', alpha=0.8)
            lane = lane + 1
            
        ax.set_xlabel('MapQ')
        ax.set_ylabel('Lanes')
        ax.set_zlabel('Fragments')        
                
        #http://people.duke.edu/~ccc14/pcfb/numpympl/MatplotlibBarPlots.html
        pylab.savefig(self.png_mapq_histogram)
        
        plt.close(figure) 
Example 25
Project: OpenTrader   Author: OpenTrading   File: backtester.py    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
def backtest_plot(self):
        """
==== OTCmd2 backtest plot

Plot the servings the chef has cooked, using matplotlib.
{{{
back plot show      - show the current plot
back plot trades    - plot the trades
back plot equity    - plot the cumulative equity
}}}
        """
        lArgs = self.lArgs
        sDo = 'plot'
        #!WTF local variable '__doc__' referenced before assignment
        self.dhelp['plot'] = __doc__
        lArgs = self.lArgs

        __doc__ = sBACplot__doc__
        _lCmds = ['show', 'trades', 'equity']
        if not hasattr(oOm, 'oBt') or not oOm.oBt:
            self.vError("You must use \"chef cook\" before you can plot")
            return
        # FixMe:
        oBt = oOm.oBt

        assert len(lArgs) > 1, "ERROR: " +sDo +str(_lCmds)
        sCmd = lArgs[1]
        assert sCmd in _lCmds, "ERROR: " +sDo +str(_lCmds)

        import matplotlib
        import matplotlib.pylab as pylab
        if sCmd == 'show':
            pylab.show()
            return

        # FixMe:
        matplotlib.rcParams['figure.figsize'] = (10, 5)

        if sCmd == 'equity':
            # FixMe: derive the period from the sTimeFrame
            sPeriod = 'W'
            close_label = 'C'
            mOhlc = oRecipe.dIngredients['mOhlc']
            oChefModule.vPlotEquity(oBt.equity, mOhlc, sTitle="%s\nEquity" % repr(oBt),
                                    sPeriod=sPeriod,
                                    close_label=close_label,
                                    )
            pylab.show()
            return

        if sCmd == 'trades':
            oBt.vPlotTrades()
            pylab.legend(loc='lower left')
            pylab.show()

            return
        self.vError("Unrecognized plot command: " + str(lArgs))
        return 
Example 26
Project: Computable   Author: ktraunmueller   File: pylabtools.py    License: MIT License 4 votes vote down vote up
def configure_inline_support(shell, backend):
    """Configure an IPython shell object for matplotlib use.

    Parameters
    ----------
    shell : InteractiveShell instance

    backend : matplotlib backend
    """
    # If using our svg payload backend, register the post-execution
    # function that will pick up the results for display.  This can only be
    # done with access to the real shell object.

    # Note: if we can't load the inline backend, then there's no point
    # continuing (such as in terminal-only shells in environments without
    # zeromq available).
    try:
        from IPython.kernel.zmq.pylab.backend_inline import InlineBackend
    except ImportError:
        return
    from matplotlib import pyplot

    cfg = InlineBackend.instance(parent=shell)
    cfg.shell = shell
    if cfg not in shell.configurables:
        shell.configurables.append(cfg)

    if backend == backends['inline']:
        from IPython.kernel.zmq.pylab.backend_inline import flush_figures
        shell.register_post_execute(flush_figures)

        # Save rcParams that will be overwrittern
        shell._saved_rcParams = dict()
        for k in cfg.rc:
            shell._saved_rcParams[k] = pyplot.rcParams[k]
        # load inline_rc
        pyplot.rcParams.update(cfg.rc)
    else:
        from IPython.kernel.zmq.pylab.backend_inline import flush_figures
        if flush_figures in shell._post_execute:
            shell._post_execute.pop(flush_figures)
        if hasattr(shell, '_saved_rcParams'):
            pyplot.rcParams.update(shell._saved_rcParams)
            del shell._saved_rcParams

    # Setup the default figure format
    select_figure_format(shell, cfg.figure_format) 
Example 27
Project: Computable   Author: ktraunmueller   File: pylab.py    License: MIT License 4 votes vote down vote up
def pylab(self, line=''):
        """Load numpy and matplotlib to work interactively.

        This function lets you activate pylab (matplotlib, numpy and
        interactive support) at any point during an IPython session.
        
        %pylab makes the following imports::
        
            import numpy
            import matplotlib
            from matplotlib import pylab, mlab, pyplot
            np = numpy
            plt = pyplot
            
            from IPython.display import display
            from IPython.core.pylabtools import figsize, getfigs
            
            from pylab import *
            from numpy import *

        If you pass `--no-import-all`, the last two `*` imports will be excluded.
        
        See the %matplotlib magic for more details about activating matplotlib
        without affecting the interactive namespace.
        """
        args = magic_arguments.parse_argstring(self.pylab, line)
        if args.no_import_all is None:
            # get default from Application
            if Application.initialized():
                app = Application.instance()
                try:
                    import_all = app.pylab_import_all
                except AttributeError:
                    import_all = True
            else:
                # nothing specified, no app - default True
                import_all = True
        else:
            # invert no-import flag
            import_all = not args.no_import_all

        gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
        self._show_matplotlib_backend(args.gui, backend)
        print ("Populating the interactive namespace from numpy and matplotlib")
        if clobbered:
            warn("pylab import has clobbered these variables: %s"  % clobbered +
            "\n`%pylab --no-import-all` prevents importing * from pylab and numpy"
            ) 
Example 28
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: backend_wx.py    License: MIT License 4 votes vote down vote up
def _print_image(self, filename, filetype, *args, **kwargs):
        origBitmap = self.bitmap

        l, b, width, height = self.figure.bbox.bounds
        width = math.ceil(width)
        height = math.ceil(height)

        self.bitmap = wx.Bitmap(width, height)

        renderer = RendererWx(self.bitmap, self.figure.dpi)

        gc = renderer.new_gc()

        self.figure.draw(renderer)

        # image is the object that we call SaveFile on.
        image = self.bitmap
        # set the JPEG quality appropriately.  Unfortunately, it is only
        # possible to set the quality on a wx.Image object.  So if we
        # are saving a JPEG, convert the wx.Bitmap to a wx.Image,
        # and set the quality.
        if filetype == wx.BITMAP_TYPE_JPEG:
            jpeg_quality = kwargs.get('quality',
                                      rcParams['savefig.jpeg_quality'])
            image = self.bitmap.ConvertToImage()
            image.SetOption(wx.IMAGE_OPTION_QUALITY, str(jpeg_quality))

        # Now that we have rendered into the bitmap, save it to the appropriate
        # file type and clean up.
        if isinstance(filename, str):
            if not image.SaveFile(filename, filetype):
                raise RuntimeError(f'Could not save figure to {filename}')
        elif cbook.is_writable_file_like(filename):
            if not isinstance(image, wx.Image):
                image = image.ConvertToImage()
            if not image.SaveStream(filename, filetype):
                raise RuntimeError(f'Could not save figure to {filename}')

        # Restore everything to normal
        self.bitmap = origBitmap

        # Note: draw is required here since bits of state about the
        # last renderer are strewn about the artist draw methods.  Do
        # not remove the draw without first verifying that these have
        # been cleaned up.  The artist contains() methods will fail
        # otherwise.
        if self._isDrawn:
            self.draw()
        self.Refresh()


########################################################################
#
# The following functions and classes are for pylab compatibility
# mode (matplotlib.pylab) and implement figure managers, etc...
#
######################################################################## 
Example 29
Project: CogAlg   Author: boris-kz   File: backend_wx.py    License: MIT License 4 votes vote down vote up
def _print_image(self, filename, filetype, *args, **kwargs):
        origBitmap = self.bitmap

        l, b, width, height = self.figure.bbox.bounds
        width = math.ceil(width)
        height = math.ceil(height)

        self.bitmap = wx.Bitmap(width, height)

        renderer = RendererWx(self.bitmap, self.figure.dpi)

        gc = renderer.new_gc()

        self.figure.draw(renderer)

        # image is the object that we call SaveFile on.
        image = self.bitmap
        # set the JPEG quality appropriately.  Unfortunately, it is only
        # possible to set the quality on a wx.Image object.  So if we
        # are saving a JPEG, convert the wx.Bitmap to a wx.Image,
        # and set the quality.
        if filetype == wx.BITMAP_TYPE_JPEG:
            jpeg_quality = kwargs.get('quality',
                                      rcParams['savefig.jpeg_quality'])
            image = self.bitmap.ConvertToImage()
            image.SetOption(wx.IMAGE_OPTION_QUALITY, str(jpeg_quality))

        # Now that we have rendered into the bitmap, save it to the appropriate
        # file type and clean up.
        if isinstance(filename, str):
            if not image.SaveFile(filename, filetype):
                raise RuntimeError(f'Could not save figure to {filename}')
        elif cbook.is_writable_file_like(filename):
            if not isinstance(image, wx.Image):
                image = image.ConvertToImage()
            if not image.SaveStream(filename, filetype):
                raise RuntimeError(f'Could not save figure to {filename}')

        # Restore everything to normal
        self.bitmap = origBitmap

        # Note: draw is required here since bits of state about the
        # last renderer are strewn about the artist draw methods.  Do
        # not remove the draw without first verifying that these have
        # been cleaned up.  The artist contains() methods will fail
        # otherwise.
        if self._isDrawn:
            self.draw()
        self.Refresh()


########################################################################
#
# The following functions and classes are for pylab compatibility
# mode (matplotlib.pylab) and implement figure managers, etc...
#
########################################################################