예제 #1
0
    def assert_no_legend_overlap(self, m="Legends overlap eachother"):
        """When multiple legends on ax, asserts that there are no two legends
        in ax that overlap each other

        Parameters
        ----------
        m: string error message if assertion is not met

        Returns
        -------
        Nothing (if checks pass) or prints error message m
        """
        legends = self.get_legends()
        n = len(legends)
        for i in range(n - 1):
            # Get extent of first legend in check, RendererBase() avoids error
            leg_extent1 = (
                legends[i].get_window_extent(RendererBase()).get_points()
            )
            for j in range(i + 1, n):
                # Get extent of second legend in check
                leg_extent2 = (
                    legends[j].get_window_extent(RendererBase()).get_points()
                )
                assert (
                    self.legends_overlap(leg_extent1, leg_extent2) == False
                ), m
예제 #2
0
    def __init__(self, figure, fh, dummy=False):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes:
        * figure: Matplotlib figure to initialize height, width and dpi from.
        * fh: File handle for the output of the drawing commands.
        """
        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        # get LatexManager instance
        self.latexManager = LatexManagerFactory.get_latex_manager()

        if dummy:
            # dummy==True deactivate all methods
            nop = lambda *args, **kwargs: None
            for m in RendererPgf.__dict__.keys():
                if m.startswith("draw_"):
                    self.__dict__[m] = nop
        else:
            # if fh does not belong to a filename, deactivate draw_image
            if not os.path.exists(fh.name):
                self.__dict__["draw_image"] = lambda *args, **kwargs: None
예제 #3
0
 def __init__(self, dpi, width, height):
     RendererBase.__init__(self)
     self.dpi = dpi
     self.width = width
     self.height = height
     self.gc = GraphicsContextMac()
     self.mathtext_parser = MathTextParser('MacOSX')
예제 #4
0
    def __init__(self, width, height, dpi):
        if __debug__: verbose.report('RendererAgg.__init__', 'debug-annoying')
        RendererBase.__init__(self)
        self.dpi = dpi
        self.width = width
        self.height = height
        if __debug__: verbose.report('RendererAgg.__init__ width=%s, \
                        height=%s'%(width, height), 'debug-annoying')
        self._renderer = _RendererAgg(int(width), int(height), dpi.get(),
                                    debug=False)
        if __debug__: verbose.report('RendererAgg.__init__ _RendererAgg done',
                                     'debug-annoying')
        self.draw_polygon = self._renderer.draw_polygon
        self.draw_rectangle = self._renderer.draw_rectangle
        self.draw_path = self._renderer.draw_path
        self.draw_lines = self._renderer.draw_lines
        self.draw_markers = self._renderer.draw_markers
        self.draw_image = self._renderer.draw_image
        self.draw_line_collection = self._renderer.draw_line_collection
        self.draw_quad_mesh = self._renderer.draw_quad_mesh
        self.draw_poly_collection = self._renderer.draw_poly_collection
        self.draw_regpoly_collection = self._renderer.draw_regpoly_collection

        self.copy_from_bbox = self._renderer.copy_from_bbox
        self.restore_region = self._renderer.restore_region
        self.mathtext_parser = MathTextParser('Agg')

        self.bbox = lbwh_to_bbox(0,0, self.width, self.height)
        if __debug__: verbose.report('RendererAgg.__init__ done',
                                     'debug-annoying')
예제 #5
0
 def __init__(self, dpi):
     self.dpi = dpi
     self.gc = GraphicsContextCairo(renderer=self)
     self.text_ctx = cairo.Context(
        cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
     self.mathtext_parser = MathTextParser('Cairo')
     RendererBase.__init__(self)
예제 #6
0
 def _for_fmt_output(cls, fmt, stream, width, height, dpi):
     if stream is not None and cbook.file_requires_unicode(stream):
         if fmt in [_StreamSurfaceType.PS, _StreamSurfaceType.EPS]:
             # PS is (typically) ASCII -- Language Reference, section 3.2.
             stream = _BytesWritingWrapper(stream, "ascii")
         elif fmt is _StreamSurfaceType.SVG:
             # cairo outputs SVG with encoding="UTF-8".
             stream = _BytesWritingWrapper(stream, "utf-8")
         # (No default encoding for pdf, which is a binary format.)
     args = fmt, stream, width, height, dpi
     cairo_debug_pdf = os.environ.get("CAIRO_DEBUG_PDF")
     if mpl.rcParams["pdf.compression"]:
         os.environ.setdefault("CAIRO_DEBUG_PDF", "1")
     try:
         obj = _mplcairo.GraphicsContextRendererCairo.__new__(cls, *args)
         _mplcairo.GraphicsContextRendererCairo.__init__(obj, *args)
     finally:
         if cairo_debug_pdf is None:
             os.environ.pop("CAIRO_DEBUG_PDF", None)
         else:
             os.environ["CAIRO_DEBUG_PDF"] = cairo_debug_pdf
     try:
         name = os.fsdecode(stream.name)
     except (AttributeError, TypeError):
         pass  # In particular, stream.name is an int for TemporaryFile.
     else:
         obj._set_path(name)
     RendererBase.__init__(obj)
     return obj
예제 #7
0
    def __init__(self, width, height, svgwriter, basename=None, image_dpi=72):
        self.width = width
        self.height = height
        self.writer = XMLWriter(svgwriter)
        self.image_dpi = image_dpi  # the actual dpi we want to rasterize stuff with

        self._groupd = {}
        if not rcParams['svg.image_inline']:
            assert basename is not None
            self.basename = basename
            self._imaged = {}
        self._clipd = OrderedDict()
        self._char_defs = {}
        self._markers = {}
        self._path_collection_id = 0
        self._imaged = {}
        self._hatchd = OrderedDict()
        self._has_gouraud = False
        self._n_gradients = 0
        self._fonts = OrderedDict()
        self.mathtext_parser = MathTextParser('SVG')

        RendererBase.__init__(self)
        self._glyph_map = dict()

        svgwriter.write(svgProQgsFmvLog)
        self._start_id = self.writer.start(
            'svg',
            width='%ipt' % width, height='%ipt' % height,
            viewBox='0 0 %i %i' % (width, height),
            xmlns="http://www.w3.org/2000/svg",
            version="1.1",
            attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"})
        self._write_default_style()
예제 #8
0
    def __init__(self, figure, fh, dummy=False):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes:
        * figure: Matplotlib figure to initialize height, width and dpi from.
        * fh: File handle for the output of the drawing commands.
        """
        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        # get LatexManager instance
        self.latexManager = LatexManagerFactory.get_latex_manager()

        if dummy:
            # dummy==True deactivate all methods
            nop = lambda *args, **kwargs: None
            for m in RendererPgf.__dict__.keys():
                if m.startswith("draw_"):
                    self.__dict__[m] = nop
        else:
            # if fh does not belong to a filename, deactivate draw_image
            if not hasattr(fh, 'name') or not os.path.exists(fh.name):
                warnings.warn("streamed pgf-code does not support raster "
                              "graphics, consider using the pgf-to-pdf option",
                              UserWarning)
                self.__dict__["draw_image"] = lambda *args, **kwargs: None
예제 #9
0
    def __init__(self, figure, fh, dummy=False):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes
        ----------
        figure : `matplotlib.figure.Figure`
            Matplotlib figure to initialize height, width and dpi from.
        fh : file-like
            File handle for the output of the drawing commands.
        """

        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        # get LatexManager instance
        self.latexManager = LatexManager._get_cached_or_new()

        if dummy:
            # dummy==True deactivate all methods
            for m in RendererPgf.__dict__:
                if m.startswith("draw_"):
                    self.__dict__[m] = lambda *args, **kwargs: None
        else:
            # if fh does not belong to a filename, deactivate draw_image
            if not hasattr(fh, 'name') or not os.path.exists(fh.name):
                cbook._warn_external("streamed pgf-code does not support "
                                     "raster graphics, consider using the "
                                     "pgf-to-pdf option", UserWarning)
                self.__dict__["draw_image"] = lambda *args, **kwargs: None
예제 #10
0
    def assert_legend_no_overlay_content(self,
                                         message="Legend overlays plot window"
                                         ):
        """Asserts that each legend does not overlay plot window

        Parameters
        ----------
        message : string
            The error message to be displayed if the legend overlays the plot
            window.

        Raises
        -------
        AssertionError
            with message `m` if legend does not overlay plot window
        """
        # RendererBase() is needed to get extent, otherwise raises an error
        plot_extent = self.ax.get_window_extent(RendererBase()).get_points()
        legends = self.get_legends()
        for leg in legends:
            # RendererBase() is needed to get extent, otherwise raises error
            leg_extent = leg.get_window_extent(RendererBase()).get_points()
            legend_left = leg_extent[1][0] < plot_extent[0][0]
            legend_right = leg_extent[0][0] > plot_extent[1][0]
            legend_below = leg_extent[1][1] < plot_extent[0][1]
            assert legend_left or legend_right or legend_below, message
예제 #11
0
    def assert_no_legend_overlap(self, message="Legends overlap eachother"):
        """When multiple legends on ax, asserts that there are no two legends
        in ax that overlap each other

        Parameters
        ----------
        message : string
            The error message to be displayed if two legends overlap.

        Raises
        -------
        AssertionError
            with message `m` if legends overlap
        """
        legends = self.get_legends()
        n = len(legends)
        for i in range(n - 1):
            # Get extent of first legend in check, RendererBase() avoids error
            leg_extent1 = (legends[i].get_window_extent(
                RendererBase()).get_points())
            for j in range(i + 1, n):
                # Get extent of second legend in check
                leg_extent2 = (legends[j].get_window_extent(
                    RendererBase()).get_points())
                assert not self.legends_overlap(leg_extent1,
                                                leg_extent2), message
예제 #12
0
    def __init__(self, width, height, dpi):
        if __debug__: verbose.report('RendererAgg.__init__', 'debug-annoying')
        RendererBase.__init__(self)
        self.dpi = dpi
        self.width = width
        self.height = height
        if __debug__:
            verbose.report(
                'RendererAgg.__init__ width=%s, height=%s' % (width, height),
                'debug-annoying')
        self._renderer = _RendererAgg(int(width),
                                      int(height),
                                      dpi,
                                      debug=False)
        if __debug__:
            verbose.report('RendererAgg.__init__ _RendererAgg done',
                           'debug-annoying')
        self.draw_path = self._renderer.draw_path
        self.draw_markers = self._renderer.draw_markers
        self.draw_path_collection = self._renderer.draw_path_collection
        self.draw_quad_mesh = self._renderer.draw_quad_mesh
        self.draw_image = self._renderer.draw_image
        self.copy_from_bbox = self._renderer.copy_from_bbox
        self.restore_region = self._renderer.restore_region
        self.tostring_rgba_minimized = self._renderer.tostring_rgba_minimized
        self.mathtext_parser = MathTextParser('Agg')

        self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
        if __debug__:
            verbose.report('RendererAgg.__init__ done', 'debug-annoying')
예제 #13
0
    def __init__(self, width, height, svgwriter, basename=None, image_dpi=72):
        self.width = width
        self.height = height
        self.writer = XMLWriter(svgwriter)
        self.image_dpi = image_dpi  # the actual dpi we want to rasterize stuff with

        self._groupd = {}
        if not rcParams['svg.image_inline']:
            assert basename is not None
            self.basename = basename
            self._imaged = {}
        self._clipd = OrderedDict()
        self._char_defs = {}
        self._markers = {}
        self._path_collection_id = 0
        self._imaged = {}
        self._hatchd = OrderedDict()
        self._has_gouraud = False
        self._n_gradients = 0
        self._fonts = OrderedDict()
        self.mathtext_parser = MathTextParser('SVG')

        RendererBase.__init__(self)
        self._glyph_map = dict()

        svgwriter.write(svgProlog)
        self._start_id = self.writer.start(
            'svg',
            width='%ipt' % width, height='%ipt' % height,
            viewBox='0 0 %i %i' % (width, height),
            xmlns="http://www.w3.org/2000/svg",
            version="1.1",
            attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"})
        self._write_default_style()
예제 #14
0
    def __init__(self, width, height, pswriter, dpi=72):
        RendererBase.__init__(self)
        self.width = width
        self.height = height
        self._pswriter = pswriter
        if rcParams['text.usetex']:
            self.textcnt = 0
            self.psfrag = []
        self.dpi = dpi

        # current renderer state (None=uninitialised)
        self.color = None
        self.linewidth = None
        self.linejoin = None
        self.linecap = None
        self.linedash = None
        self.fontname = None
        self.fontsize = None
        self.hatch = None
        self.image_magnification = dpi / 72.0
        self._clip_paths = {}
        self._path_collection_id = 0

        self.used_characters = {}
        self.mathtext_parser = MathTextParser("PS")
예제 #15
0
    def __init__(self, figure, fh, dummy=False):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes
        ----------
        figure : `matplotlib.figure.Figure`
            Matplotlib figure to initialize height, width and dpi from.
        fh : file-like
            File handle for the output of the drawing commands.
        """

        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        self._latexManager = LatexManager._get_cached_or_new()  # deprecated

        if dummy:
            # dummy==True deactivate all methods
            for m in RendererPgf.__dict__:
                if m.startswith("draw_"):
                    self.__dict__[m] = lambda *args, **kwargs: None
        else:
            # if fh does not belong to a filename, deactivate draw_image
            if not hasattr(fh, 'name') or not os.path.exists(fh.name):
                self.__dict__["draw_image"] = \
                    lambda *args, **kwargs: cbook._warn_external(
                        "streamed pgf-code does not support raster graphics, "
                        "consider using the pgf-to-pdf option")
예제 #16
0
    def __init__(self, width, height, svgwriter, basename=None):
        self.width = width
        self.height = height
        self.writer = XMLWriter(svgwriter)

        self._groupd = {}
        if not rcParams["svg.image_inline"]:
            assert basename is not None
            self.basename = basename
            self._imaged = {}
        self._clipd = {}
        self._char_defs = {}
        self._markers = {}
        self._path_collection_id = 0
        self._imaged = {}
        self._hatchd = {}
        self._has_gouraud = False
        self._n_gradients = 0
        self._fonts = {}
        self.mathtext_parser = MathTextParser("SVG")

        RendererBase.__init__(self)
        self._glyph_map = dict()

        svgwriter.write(svgProlog)
        self._start_id = self.writer.start(
            u"svg",
            width=u"%ipt" % width,
            height="%ipt" % height,
            viewBox=u"0 0 %i %i" % (width, height),
            xmlns=u"http://www.w3.org/2000/svg",
            version=u"1.1",
            attrib={u"xmlns:xlink": u"http://www.w3.org/1999/xlink"},
        )
        self._write_default_style()
예제 #17
0
 def from_pycairo_ctx(cls, ctx, width, height, dpi, orig_scale):
     obj = _mplcairo.GraphicsContextRendererCairo.__new__(
         cls, ctx, width, height, dpi, orig_scale)
     _mplcairo.GraphicsContextRendererCairo.__init__(
         obj, ctx, width, height, dpi, orig_scale)
     RendererBase.__init__(obj)
     return obj
예제 #18
0
    def __init__(self, figure, fh, dummy=False):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes
        ----------
        figure : `matplotlib.figure.Figure`
            Matplotlib figure to initialize height, width and dpi from.
        fh : file-like
            File handle for the output of the drawing commands.
        """

        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        self._latexManager = LatexManager._get_cached_or_new()  # deprecated

        if dummy:
            # dummy==True deactivate all methods
            for m in RendererPgf.__dict__:
                if m.startswith("draw_"):
                    self.__dict__[m] = lambda *args, **kwargs: None
예제 #19
0
    def __init__(self, width, height, dpi):
        if __debug__: verbose.report('RendererAgg.__init__', 'debug-annoying')
        RendererBase.__init__(self)
        self.texd = maxdict(50)  # a cache of tex image rasters
        self._fontd = maxdict(50)

        self.dpi = dpi
        self.width = width
        self.height = height
        if __debug__:
            verbose.report(
                'RendererAgg.__init__ width=%s, height=%s' % (width, height),
                'debug-annoying')
        self._renderer = _RendererAgg(int(width),
                                      int(height),
                                      dpi,
                                      debug=False)
        self._filter_renderers = []

        if __debug__:
            verbose.report('RendererAgg.__init__ _RendererAgg done',
                           'debug-annoying')

        self._update_methods()
        self.mathtext_parser = MathTextParser('Agg')

        self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
        if __debug__:
            verbose.report('RendererAgg.__init__ done', 'debug-annoying')
예제 #20
0
    def __init__(self, width, height, svgwriter, basename=None, image_dpi=72):
        self.width = width
        self.height = height
        self.writer = XMLWriter(svgwriter)
        self.image_dpi = image_dpi  # actual dpi at which we rasterize stuff

        self._groupd = {}
        self.basename = basename
        self._image_counter = itertools.count()
        self._clipd = OrderedDict()
        self._markers = {}
        self._path_collection_id = 0
        self._hatchd = OrderedDict()
        self._has_gouraud = False
        self._n_gradients = 0
        self._fonts = OrderedDict()
        self.mathtext_parser = MathTextParser('SVG')

        RendererBase.__init__(self)
        self._glyph_map = dict()
        str_height = short_float_fmt(height)
        str_width = short_float_fmt(width)
        svgwriter.write(svgProlog)
        self._start_id = self.writer.start(
            'svg',
            width='%spt' % str_width,
            height='%spt' % str_height,
            viewBox='0 0 %s %s' % (str_width, str_height),
            xmlns="http://www.w3.org/2000/svg",
            version="1.1",
            attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"})
        self._write_default_style()
예제 #21
0
 def __init__(self, width, height, dpi, dxfversion):
     RendererBase.__init__(self)
     self.height = height
     self.width = width
     self.dpi = dpi
     self.dxfversion = dxfversion
     self._init_drawing()
예제 #22
0
    def __init__(self, width, height, pswriter, dpi=72):
        RendererBase.__init__(self)
        self.width = width
        self.height = height
        self._pswriter = pswriter
        if rcParams['text.usetex']:
            self.textcnt = 0
            self.psfrag = []
        self.dpi = dpi

        # current renderer state (None=uninitialised)
        self.color = None
        self.linewidth = None
        self.linejoin = None
        self.linecap = None
        self.linedash = None
        self.fontname = None
        self.fontsize = None
        self.hatch = None
        self.image_magnification = dpi/72.0
        self._clip_paths = {}
        self._path_collection_id = 0

        self.used_characters = {}
        self.mathtext_parser = MathTextParser("PS")
예제 #23
0
 def __init__(self, dpi, width, height):
     RendererBase.__init__(self)
     self.dpi = dpi
     self.width = width
     self.height = height
     self.gc = GraphicsContextMac()
     self.mathtext_parser = MathTextParser('MacOSX')
예제 #24
0
    def __init__(self, width, height, dpi):
        if __debug__:
            verbose.report("RendererAgg.__init__", "debug-annoying")
        RendererBase.__init__(self)
        self.dpi = dpi
        self.width = width
        self.height = height
        if __debug__:
            verbose.report(
                "RendererAgg.__init__ width=%s, \
                        height=%s"
                % (width, height),
                "debug-annoying",
            )
        self._renderer = _RendererAgg(int(width), int(height), dpi.get(), debug=False)
        if __debug__:
            verbose.report("RendererAgg.__init__ _RendererAgg done", "debug-annoying")
        self.draw_polygon = self._renderer.draw_polygon
        self.draw_rectangle = self._renderer.draw_rectangle
        self.draw_path = self._renderer.draw_path
        self.draw_lines = self._renderer.draw_lines
        self.draw_markers = self._renderer.draw_markers
        self.draw_image = self._renderer.draw_image
        self.draw_line_collection = self._renderer.draw_line_collection
        self.draw_quad_mesh = self._renderer.draw_quad_mesh
        self.draw_poly_collection = self._renderer.draw_poly_collection
        self.draw_regpoly_collection = self._renderer.draw_regpoly_collection

        self.copy_from_bbox = self._renderer.copy_from_bbox
        self.restore_region = self._renderer.restore_region
        self.mathtext_parser = MathTextParser("Agg")

        self.bbox = lbwh_to_bbox(0, 0, self.width, self.height)
        if __debug__:
            verbose.report("RendererAgg.__init__ done", "debug-annoying")
예제 #25
0
    def __init__(self, width, height, ipewriter, basename):
        self.width = width
        self.height = height
        self.writer = XMLWriter(ipewriter)
        self.basename = basename

        RendererBase.__init__(self)

        # use same latex as Ipe (default is xelatex)
        rcParams['pgf.texsystem'] = "pdflatex"
        self.latexManager = None
        if rcParams.get("ipe.textsize", False):
            self.latexManager = LatexManagerFactory.get_latex_manager()

        self._start_id = self.writer.start(
            u'ipe',
            version=u"70005",
            creator="matplotlib")
        pre = rcParams.get('ipe.preamble', "")
        if pre != "":
            self.writer.start(u'preamble')
            self.writer.data(pre)
            self.writer.end(indent=False)
        sheet = rcParams.get('ipe.stylesheet', "")
        if sheet != "":
            self.writer.insertSheet(sheet)
        self.writer.start(u'ipestyle', name=u"opacity")

        for i in range(10,100,10):
            self.writer.element(u'opacity', name=u'%02d%%'% i, 
                                value=u'%g'% (i/100.0))
        self.writer.end()
        self.writer.start(u'page')
예제 #26
0
    def __init__(self, width, height, dpi):
        if __debug__: verbose.report('RendererAgg.__init__', 'debug-annoying')
        RendererBase.__init__(self)
        self.texd = maxdict(50)  # a cache of tex image rasters
        self._fontd = maxdict(50)

        self.dpi = dpi
        self.width = width
        self.height = height
        if __debug__: verbose.report('RendererAgg.__init__ width=%s, height=%s'%(width, height), 'debug-annoying')
        self._renderer = _RendererAgg(int(width), int(height), dpi, debug=False)
        if __debug__: verbose.report('RendererAgg.__init__ _RendererAgg done',
                                     'debug-annoying')
        #self.draw_path = self._renderer.draw_path  # see below
        self.draw_markers = self._renderer.draw_markers
        self.draw_path_collection = self._renderer.draw_path_collection
        self.draw_quad_mesh = self._renderer.draw_quad_mesh
        self.draw_image = self._renderer.draw_image
        self.copy_from_bbox = self._renderer.copy_from_bbox
        self.tostring_rgba_minimized = self._renderer.tostring_rgba_minimized
        self.mathtext_parser = MathTextParser('Agg')

        self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
        if __debug__: verbose.report('RendererAgg.__init__ done',
                                     'debug-annoying')
예제 #27
0
    def __init__(self, width, height, pswriter, imagedpi=72):
        """
        Although postscript itself is dpi independent, we need to
        imform the image code about a requested dpi to generate high
        res images and them scale them before embeddin them
        """
        RendererBase.__init__(self)
        self.width = width
        self.height = height
        self._pswriter = pswriter
        if rcParams['text.usetex']:
            self.textcnt = 0
            self.psfrag = []
        self.imagedpi = imagedpi
        if rcParams['path.simplify']:
            self.simplify = (width * imagedpi, height * imagedpi)
        else:
            self.simplify = None

        # current renderer state (None=uninitialised)
        self.color = None
        self.linewidth = None
        self.linejoin = None
        self.linecap = None
        self.linedash = None
        self.fontname = None
        self.fontsize = None
        self._hatches = {}
        self.image_magnification = imagedpi/72.0
        self._clip_paths = {}
        self._path_collection_id = 0

        self.used_characters = {}
        self.mathtext_parser = MathTextParser("PS")
예제 #28
0
 def __init__(self, dpi):
     self.dpi = dpi
     self.gc = GraphicsContextCairo(renderer=self)
     self.text_ctx = cairo.Context(
        cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
     self.mathtext_parser = MathTextParser('Cairo')
     RendererBase.__init__(self)
예제 #29
0
 def __init__(self, dpi, width, height):
     RendererBase.__init__(self)
     self.dpi = dpi
     self.width = width
     self.height = height
     self.gc = GraphicsContextIos()
     self.gc.set_dpi(self.dpi)
     self.mathtext_parser = MathTextParser('ios')
 def __init__(self, l, b, w, h, dpi, bbox, draw_point_callback, draw_sign_callback):
     RendererBase.__init__(self)
     self.l = l
     self.b = b
     self.w = w
     self.h = h
     self.dpi = dpi
     self.bbox = bbox
     self.dpc = draw_point_callback
     self.dsc = draw_sign_callback
예제 #31
0
    def __init__(self, dpi):
        """
        """
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))
        self.dpi = dpi
        self.gc = GraphicsContextCairo(renderer=self)
        self.text_ctx = cairo.Context(
            cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
        self.mathtext_parser = MathTextParser('Cairo')

        RendererBase.__init__(self)
예제 #32
0
    def __init__(self, dpi):
        """
        """
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))
        self.dpi = dpi
        self.gc = GraphicsContextCairo (renderer=self)
        self.text_ctx = cairo.Context (
           cairo.ImageSurface (cairo.FORMAT_ARGB32,1,1))
        self.mathtext_parser = MathTextParser('Cairo')

        RendererBase.__init__(self)
예제 #33
0
파일: base.py 프로젝트: greglucas/mplcairo
 def _for_fmt_output(cls, fmt, stream, width, height, dpi):
     args = fmt, stream, width, height, dpi
     obj = _mplcairo.GraphicsContextRendererCairo.__new__(cls, *args)
     _mplcairo.GraphicsContextRendererCairo.__init__(obj, *args)
     try:
         name = os.fsdecode(stream.name)
     except (AttributeError, TypeError):
         pass  # In particular, stream.name is an int for TemporaryFile.
     else:
         obj._set_path(name)
     RendererBase.__init__(obj)
     return obj
예제 #34
0
    def __init__(self, width, height, dpi):
        RendererBase.__init__(self)

        self.dpi = dpi
        self.width = width
        self.height = height
        self._renderer = _RendererAgg(int(width), int(height), dpi)
        self._filter_renderers = []

        self._update_methods()
        self.mathtext_parser = MathTextParser('Agg')

        self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
예제 #35
0
    def __init__(self, width, height, dpi):
        RendererBase.__init__(self)

        self.dpi = dpi
        self.width = width
        self.height = height
        self._renderer = _RendererAgg(int(width), int(height), dpi)
        self._filter_renderers = []

        self._update_methods()
        self.mathtext_parser = MathTextParser('Agg')

        self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
예제 #36
0
    def restore_region(self, region, bbox=None, xy=None):
        return RendererBase.restore_region(self, region, bbox=None, xy=None)
        """
        Restore the saved region. If bbox (instance of BboxBase, or
        its extents) is given, only the region specified by the bbox
        will be restored. *xy* (a tuple of two floasts) optionally
        specifies the new position (the LLC of the original region,
        not the LLC of the bbox) where the region will be restored.

        >>> region = renderer.copy_from_bbox()
        >>> x1, y1, x2, y2 = region.get_extents()
        >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
        ...                         xy=(x1-dx, y1))

        """
        if bbox is not None or xy is not None:
            if bbox is None:
                x1, y1, x2, y2 = region.get_extents()
            elif isinstance(bbox, BboxBase):
                x1, y1, x2, y2 = bbox.extents
            else:
                x1, y1, x2, y2 = bbox

            if xy is None:
                ox, oy = x1, y1
            else:
                ox, oy = xy

            self._renderer.restore_region2(region, x1, y1, x2, y2, ox, oy)

        else:
            self._renderer.restore_region(region)
예제 #37
0
    def restore_region(self, region, bbox=None, xy=None):
        return RendererBase.restore_region(self, region, bbox=None, xy=None)
        """
        Restore the saved region. If bbox (instance of BboxBase, or
        its extents) is given, only the region specified by the bbox
        will be restored. *xy* (a tuple of two floasts) optionally
        specifies the new position (the LLC of the original region,
        not the LLC of the bbox) where the region will be restored.

        >>> region = renderer.copy_from_bbox()
        >>> x1, y1, x2, y2 = region.get_extents()
        >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
        ...                         xy=(x1-dx, y1))

        """
        if bbox is not None or xy is not None:
            if bbox is None:
                x1, y1, x2, y2 = region.get_extents()
            elif isinstance(bbox, BboxBase):
                x1, y1, x2, y2 = bbox.extents
            else:
                x1, y1, x2, y2 = bbox

            if xy is None:
                ox, oy = x1, y1
            else:
                ox, oy = xy

            self._renderer.restore_region2(region, x1, y1, x2, y2, ox, oy)

        else:
            self._renderer.restore_region(region)
예제 #38
0
    def _draw_text_as_path(self, renderer, gc, x, y, s, prop, angle, ismath):

        path, transform = RendererBase._get_text_path_transform(
            renderer, x, y, s, prop, angle, ismath)
        color = gc.get_rgb()[:3]

        gc.set_linewidth(0.0)
        self.draw_path(renderer, gc, path, transform, rgbFace=color)
    def __init__(self, figure, fh):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes:
        * figure: Matplotlib figure to initialize height, width and dpi from.
        * fh: File handle for the output of the drawing commands.
        """
        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        # get LatexManager instance
        self.latexManager = LatexManagerFactory.get_latex_manager()
예제 #40
0
 def check(master_transform, paths, all_transforms,
           offsets, facecolors, edgecolors):
     rb = RendererBase()
     raw_paths = list(rb._iter_collection_raw_paths(
         master_transform, paths, all_transforms))
     gc = rb.new_gc()
     ids = [path_id for xo, yo, path_id, gc0, rgbFace in
            rb._iter_collection(gc, master_transform, all_transforms,
                                range(len(raw_paths)), offsets,
                                transforms.IdentityTransform(),
                                facecolors, edgecolors, [], [], [False],
                                [], 'data')]
     uses = rb._iter_collection_uses_per_path(
         paths, all_transforms, offsets, facecolors, edgecolors)
     if raw_paths:
         seen = np.bincount(ids, minlength=len(raw_paths))
         assert set(seen).issubset([uses - 1, uses])
예제 #41
0
    def __init__(self, figure, fh):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes:
        * figure: Matplotlib figure to initialize height, width and dpi from.
        * fh: File handle for the output of the drawing commands.
        """
        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        # get LatexManager instance
        self.latexManager = LatexManagerFactory.get_latex_manager()
예제 #42
0
    def draw_path_collection(self, gc, master_transform, paths, all_transforms,
                             offsets, offsetTrans, facecolors, edgecolors,
                             linewidths, linestyles, antialiaseds, urls,
                             offset_position):
        # Is the optimization worth it? Rough calculation:
        # cost of emitting a path in-line is
        #    (len_path + 5) * uses_per_path
        # cost of definition+use is
        #    (len_path + 3) + 9 * uses_per_path
        len_path = len(paths[0].vertices) if len(paths) > 0 else 0
        uses_per_path = self._iter_collection_uses_per_path(
            paths, all_transforms, offsets, facecolors, edgecolors)
        should_do_optimization = \
            len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path
        if not should_do_optimization:
            return RendererBase.draw_path_collection(
                self, gc, master_transform, paths, all_transforms,
                offsets, offsetTrans, facecolors, edgecolors,
                linewidths, linestyles, antialiaseds, urls,
                offset_position)

        writer = self.writer
        path_codes = []
        writer.start('defs')
        for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
            master_transform, paths, all_transforms)):
            transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0)
            d = self._convert_path(path, transform, simplify=False)
            oid = 'C%x_%x_%s' % (self._path_collection_id, i,
                                  self._make_id('', d))
            writer.element('path', id=oid, d=d)
            path_codes.append(oid)
        writer.end('defs')

        for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
            gc, master_transform, all_transforms, path_codes, offsets,
            offsetTrans, facecolors, edgecolors, linewidths, linestyles,
            antialiaseds, urls, offset_position):
            clipid = self._get_clip(gc0)
            url = gc0.get_url()
            if url is not None:
                writer.start('a', attrib={'xlink:href': url})
            if clipid is not None:
                writer.start('g', attrib={'clip-path': 'url(#%s)' % clipid})
            attrib = {
                'xlink:href': '#%s' % path_id,
                'x': short_float_fmt(xo),
                'y': short_float_fmt(self.height - yo),
                'style': self._get_style(gc0, rgbFace)
                }
            writer.element('use', attrib=attrib)
            if clipid is not None:
                writer.end('g')
            if url is not None:
                writer.end('a')

        self._path_collection_id += 1
예제 #43
0
    def draw_path_collection(self, gc, master_transform, paths, all_transforms,
                             offsets, offsetTrans, facecolors, edgecolors,
                             linewidths, linestyles, antialiaseds, urls,
                             offset_position):
        # Is the optimization worth it? Rough calculation:
        # cost of emitting a path in-line is
        #    (len_path + 5) * uses_per_path
        # cost of definition+use is
        #    (len_path + 3) + 9 * uses_per_path
        len_path = len(paths[0].vertices) if len(paths) > 0 else 0
        uses_per_path = self._iter_collection_uses_per_path(
            paths, all_transforms, offsets, facecolors, edgecolors)
        should_do_optimization = \
            len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path
        if not should_do_optimization:
            return RendererBase.draw_path_collection(
                self, gc, master_transform, paths, all_transforms, offsets,
                offsetTrans, facecolors, edgecolors, linewidths, linestyles,
                antialiaseds, urls, offset_position)

        writer = self.writer
        path_codes = []
        writer.start('defs')
        for i, (path, transform) in enumerate(
                self._iter_collection_raw_paths(master_transform, paths,
                                                all_transforms)):
            transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0)
            d = self._convert_path(path, transform, simplify=False)
            oid = 'C%x_%x_%s' % (self._path_collection_id, i,
                                 self._make_id('', d))
            writer.element('path', id=oid, d=d)
            path_codes.append(oid)
        writer.end('defs')

        for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
                gc, master_transform, all_transforms, path_codes, offsets,
                offsetTrans, facecolors, edgecolors, linewidths, linestyles,
                antialiaseds, urls, offset_position):
            clipid = self._get_clip(gc0)
            url = gc0.get_url()
            if url is not None:
                writer.start('a', attrib={'xlink:href': url})
            if clipid is not None:
                writer.start('g', attrib={'clip-path': 'url(#%s)' % clipid})
            attrib = {
                'xlink:href': '#%s' % path_id,
                'x': short_float_fmt(xo),
                'y': short_float_fmt(self.height - yo),
                'style': self._get_style(gc0, rgbFace)
            }
            writer.element('use', attrib=attrib)
            if clipid is not None:
                writer.end('g')
            if url is not None:
                writer.end('a')

        self._path_collection_id += 1
예제 #44
0
 def start_filter(self):
     return RendererBase.start_filter(self)
     """
     Start filtering. It simply create a new canvas (the old one is saved).
     """
     self._filter_renderers.append(self._renderer)
     self._renderer = _RendererAgg(int(self.width), int(self.height),
                                   self.dpi)
     self._update_methods()
예제 #45
0
 def start_filter(self):
     return RendererBase.start_filter(self)
     """
     Start filtering. It simply create a new canvas (the old one is saved).
     """
     self._filter_renderers.append(self._renderer)
     self._renderer = _RendererAgg(int(self.width), int(self.height),
                                   self.dpi)
     self._update_methods()
예제 #46
0
 def __init__(self, width, height, dpi):
     if __debug__: verbose.report('RendererAgg.__init__', 'debug-annoying')
     RendererBase.__init__(self)
     self.texd = maxdict(50)  # a cache of tex image rasters
     self._fontd = maxdict(50)
     self.dpi = dpi
     self.width = width
     self.height = height
     if __debug__: verbose.report('RendererAgg.__init__ width=%s, height=%s'%(width, height), 'debug-annoying')
     self._renderer = _RendererAgg(int(width), int(height), dpi, debug=False)
     self._filter_renderers = []
     if __debug__: verbose.report('RendererAgg.__init__ _RendererAgg done',
                                  'debug-annoying')
     self._update_methods()
     self.mathtext_parser = MathTextParser('Agg')
     self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
     if __debug__: verbose.report('RendererAgg.__init__ done',
                                  'debug-annoying')
예제 #47
0
 def check(master_transform, paths, all_transforms,
           offsets, facecolors, edgecolors):
     rb = RendererBase()
     raw_paths = list(rb._iter_collection_raw_paths(
         master_transform, paths, all_transforms))
     gc = rb.new_gc()
     ids = [path_id for xo, yo, path_id, gc0, rgbFace in
            rb._iter_collection(gc, master_transform, all_transforms,
                                range(len(raw_paths)), offsets,
                                transforms.IdentityTransform(),
                                facecolors, edgecolors, [], [], [False],
                                [], 'data')]
     uses = rb._iter_collection_uses_per_path(
         paths, all_transforms, offsets, facecolors, edgecolors)
     seen = [0] * len(raw_paths)
     for i in ids:
         seen[i] += 1
     for n in seen:
         assert n in (uses-1, uses)
예제 #48
0
    def _draw_text_as_path(self, renderer, gc, x, y, s, prop, angle, ismath):

        path, transform = RendererBase._get_text_path_transform(renderer,
                                                                x, y, s,
                                                                prop, angle,
                                                                ismath)
        color = gc.get_rgb()[:3]

        gc.set_linewidth(0.0)
        self.draw_path(renderer, gc, path, transform, rgbFace=color)
예제 #49
0
 def _draw_text_as_path(self, renderer, gc, x, y, s, prop, angle, ismath):
     if isinstance(renderer, MixedModeRenderer):
         renderer = renderer._renderer
     path, transform = RendererBase._get_text_path_transform(renderer,
                                                             x, y, s,
                                                             prop, angle,
                                                             ismath)
     color = gc.get_rgb()[:3]
     gc.set_linewidth(0.0)
     self.draw_path(renderer, gc, path, transform, rgbFace=color)
예제 #50
0
 def __init__(self, width, height, svgwriter, basename=None):
     self.width=width
     self.height=height
     self._svgwriter = svgwriter
     self._groupd = {}
     if not rcParams['svg.image_inline']:
         assert basename is not None
         self.basename = basename
         self._imaged = {}
     self._clipd = {}
     self._char_defs = {}
     self._markers = {}
     self._path_collection_id = 0
     self._imaged = {}
     self._hatchd = {}
     self._n_gradients = 0
     self.mathtext_parser = MathTextParser('SVG')
     RendererBase.__init__(self)
     self._glyph_map = dict()
     svgwriter.write(svgProlog%(width,height,width,height))
예제 #51
0
    def _draw_text_as_path(self, renderer, gc, x, y, s, prop, angle, ismath):

        if isinstance(renderer, MixedModeRenderer):
            renderer = renderer._renderer

        path, transform = RendererBase._get_text_path_transform(
            renderer, x, y, s, prop, angle, ismath)
        color = gc.get_rgb()[:3]

        gc.set_linewidth(0.0)
        self.draw_path(renderer, gc, path, transform, rgbFace=color)
예제 #52
0
파일: base.py 프로젝트: b-xiang/mplcairo
 def _for_fmt_output(cls, fmt, stream, width, height, dpi):
     if cbook.file_requires_unicode(stream):
         if fmt in [_StreamSurfaceType.PS, _StreamSurfaceType.EPS]:
             # PS is (typically) ASCII -- Language Reference, section 3.2.
             stream = _BytesWritingWrapper(stream, "ascii")
         elif fmt is _StreamSurfaceType.SVG:
             # cairo outputs SVG with encoding="UTF-8".
             stream = _BytesWritingWrapper(stream, "utf-8")
         # (No default encoding for pdf, which is a binary format.)
     args = fmt, stream, width, height, dpi
     obj = _mplcairo.GraphicsContextRendererCairo.__new__(cls, *args)
     _mplcairo.GraphicsContextRendererCairo.__init__(obj, *args)
     try:
         name = os.fsdecode(stream.name)
     except (AttributeError, TypeError):
         pass  # In particular, stream.name is an int for TemporaryFile.
     else:
         obj._set_path(name)
     RendererBase.__init__(obj)
     return obj
예제 #53
0
    def __init__(self, width, height, svgwriter, basename=None, image_dpi=72):
        self.width = width
        self.height = height
        self.writer = XMLWriter(svgwriter)
        self.image_dpi = image_dpi  # the actual dpi we want to rasterize stuff with

        self._groupd = {}
        if not rcParams['svg.image_inline']:
            assert basename is not None
            self.basename = basename
            self._imaged = {}
        self._clipd = OrderedDict()
        self._char_defs = {}
        self._markers = {}
        self._path_collection_id = 0
        self._imaged = {}
        self._hatchd = OrderedDict()
        self._has_gouraud = False
        self._n_gradients = 0
        self._fonts = OrderedDict()
        self.mathtext_parser = MathTextParser('SVG')

        RendererBase.__init__(self)
        self._glyph_map = dict()
        str_height = short_float_fmt(height)
        str_width = short_float_fmt(width)
        svgwriter.write(svgProlog)

        # Changes starts here for Image Truncation
        # Changed from integer to float to accept decimals
        self._start_id = self.writer.start(
            'svg',
            width='%dpt' % str_width,
            height='%dpt' % str_height,
            viewBox='0 0 %d %d' % (str_width, str_height),
            xmlns="http://www.w3.org/2000/svg",
            version="1.1",
            attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"})
        self._write_default_style()
예제 #54
0
    def __init__(self, width, height, dpi):
        if __debug__:
            verbose.report("RendererAgg.__init__", "debug-annoying")
        RendererBase.__init__(self)

        self.dpi = dpi
        self.width = width
        self.height = height
        if __debug__:
            verbose.report("RendererAgg.__init__ width=%s, height=%s" % (width, height), "debug-annoying")
        self._renderer = _RendererAgg(int(width), int(height), dpi, debug=False)
        self._filter_renderers = []

        if __debug__:
            verbose.report("RendererAgg.__init__ _RendererAgg done", "debug-annoying")

        self._update_methods()
        self.mathtext_parser = MathTextParser("Agg")

        self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
        if __debug__:
            verbose.report("RendererAgg.__init__ done", "debug-annoying")
예제 #55
0
    def __init__(self, width, height, svgwriter, basename=None):
        self.width = width
        self.height = height
        self._svgwriter = svgwriter

        self._groupd = {}
        if not rcParams['svg.image_inline']:
            assert basename is not None
            self.basename = basename
            self._imaged = {}
        self._clipd = {}
        self._char_defs = {}
        self._markers = {}
        self._path_collection_id = 0
        self._imaged = {}
        self._hatchd = {}
        self._n_gradients = 0
        self.mathtext_parser = MathTextParser('SVG')

        RendererBase.__init__(self)
        self._glyph_map = dict()

        svgwriter.write(svgProlog % (width, height, width, height))
예제 #56
0
 def draw_path_collection(self, gc, master_transform, paths, all_transforms,
     offsets, offsetTrans, facecolors, edgecolors,
     linewidths, linestyles, antialiaseds, urls,
     offset_position):
     '''Draws a collection of paths selecting drawing properties from
        the lists *facecolors*, *edgecolors*, *linewidths*,
        *linestyles* and *antialiaseds*. *offsets* is a list of
        offsets to apply to each of the paths. The offsets in
        *offsets* are first transformed by *offsetTrans* before being
        applied.  *offset_position* may be either "screen" or "data"
        depending on the space that the offsets are in.
     '''
     len_path = len(paths[0].vertices) if len(paths) > 0 else 0
     uses_per_path = self._iter_collection_uses_per_path(
         paths, all_transforms, offsets, facecolors, edgecolors)
     # check whether an optimization is needed by calculating the cost of
     # generating and use a path with the cost of emitting a path in-line.
     should_do_optimization = \
         len_path + uses_per_path + 5 < len_path * uses_per_path
     if not should_do_optimization:
         return RendererBase.draw_path_collection(
             self, gc, master_transform, paths, all_transforms,
             offsets, offsetTrans, facecolors, edgecolors,
             linewidths, linestyles, antialiaseds, urls,
             offset_position)
     # Generate an array of unique paths with the respective transformations
     path_codes = []
     for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
         master_transform, paths, all_transforms)):
         transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0)
         if _mpl_ge_2_0:
             polygons = path.to_polygons(transform, closed_only=False)
         else:
             polygons = path.to_polygons(transform)
         path_codes.append(polygons)
     # Apply the styles and rgbFace to each one of the raw paths from
     # the list. Additionally a transformation is being applied to
     # translate each independent path
     for xo, yo, path_poly, gc0, rgbFace in self._iter_collection(
         gc, master_transform, all_transforms, path_codes, offsets,
         offsetTrans, facecolors, edgecolors, linewidths, linestyles,
         antialiaseds, urls, offset_position):
         list_canvas_instruction = self.get_path_instructions(gc0, path_poly,
                                 closed=True, rgbFace=rgbFace)
         for widget, instructions in list_canvas_instruction:
             widget.canvas.add(PushMatrix())
             widget.canvas.add(Translate(xo, yo))
             widget.canvas.add(instructions)
             widget.canvas.add(PopMatrix())
예제 #57
0
    def __init__(self, figure, fh, dummy=False):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes:
        * figure: Matplotlib figure to initialize height, width and dpi from.
        * fh: File handle for the output of the drawing commands.
        """
        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        # get LatexManager instance
        self.latexManager = LatexManagerFactory.get_latex_manager()

        # dummy==True deactivate all methods
        if dummy:
            nop = lambda *args, **kwargs: None
            for m in list(RendererPgf.__dict__.keys()):
                if m.startswith("draw_"):
                    self.__dict__[m] = nop
예제 #58
0
    def stop_filter(self, post_processing):
        return RendererBase.stop_filter(self, post_processing)
        """
        Save the plot in the current canvas as a image and apply
        the *post_processing* function.

           def post_processing(image, dpi):
             # ny, nx, depth = image.shape
             # image (numpy array) has RGBA channels and has a depth of 4.
             ...
             # create a new_image (numpy array of 4 channels, size can be
             # different). The resulting image may have offsets from
             # lower-left corner of the original image
             return new_image, offset_x, offset_y

        The saved renderer is restored and the returned image from
        post_processing is plotted (using draw_image) on it.
        """

        # WARNING.
        # For agg_filter to work, the rendere's method need
        # to overridden in the class. See draw_markers, and draw_path_collections

        from matplotlib._image import fromarray

        width, height = int(self.width), int(self.height)

        buffer, bounds = self._renderer.tostring_rgba_minimized()

        l, b, w, h = bounds


        self._renderer = self._filter_renderers.pop()
        self._update_methods()

        if w > 0 and h > 0:
            img = np.fromstring(buffer, np.uint8)
            img, ox, oy = post_processing(img.reshape((h, w, 4)) / 255.,
                                          self.dpi)
            image = fromarray(np.flipud(img), 1)
#            image.flipud_out()

            gc = self.new_gc()
            self._renderer.draw_image(gc,
                                      l+ox, height - b - h +oy,
                                      image)
예제 #59
0
    def draw_path_collection(self, gc, master_transform, paths, *args,
                             **kwargs):
        # We do a little shimmy so that all paths are drawn for each path
        # effect in turn. Essentially, we induce recursion (depth 1) which is
        # terminated once we have just a single path effect to work with.
        if len(self._path_effects) == 1:
            # Call the base path effect function - this uses the unoptimised
            # approach of calling "draw_path" multiple times.
            return RendererBase.draw_path_collection(self, gc,
                                                     master_transform, paths,
                                                     *args, **kwargs)

        for path_effect in self._path_effects:
            renderer = self.copy_with_path_effect([path_effect])
            # Recursively call this method, only next time we will only have
            # one path effect.
            renderer.draw_path_collection(gc, master_transform, paths,
                                          *args, **kwargs)
예제 #60
0
 def __init__(self, dpi, width, height):
     RendererBase.__init__(self)
     self.dpi = dpi
     self.width = width
     self.height = height
     self.gc = GraphicsContextMac()