Esempio n. 1
0
    def save(self, name, pdf=True, pgf=True):
        """Save figure to pgf and pdf.

        By default it saves the figure in both pdf and pgf, but this behavior
        may be adapted using ``pdf`` and ``pgf`` keyword arguments.

        Args:
            name: file name without extension
            pdf: if True saves figure in pdf format
            pgf: if True saves figure in pgf format
        """
        with mpl.rc_context(rc=self.rc.get_rc_to_function('save')):
            canvas = FigureCanvasPgf(self.fig)
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                kw = {'bbox_inches': 'tight', 'pad_inches': 0}
                if pgf:
                    canvas.print_figure(name + '.pgf', **kw)
                if pdf:
                    canvas.print_figure(name + '.pdf', **kw)
Esempio n. 2
0
    def save(self, filename, figsize=None, **kwds):
        r"""
        Save ``self`` to a file, in various formats.

        INPUT:

        - ``filename`` -- (string) the file name; the image format is given by
          the extension, which can be one of the following:

            * ``.eps``,

            * ``.pdf``,

            * ``.png``,

            * ``.ps``,

            * ``.sobj`` (for a Sage object you can load later),

            * ``.svg``,

            * empty extension will be treated as ``.sobj``.

        - ``figsize`` -- (default: ``None``) width or [width, height] in inches
          of the Matplotlib figure; if none is provided, Matplotlib's default
          (6.4 x 4.8 inches) is used

        - ``kwds`` -- keyword arguments, like ``dpi=...``, passed to the
          plotter, see :meth:`show`

        EXAMPLES::

            sage: F = tmp_filename(ext='.png')
            sage: L = [plot(sin(k*x), (x,-pi,pi)) for k in [1..3]]
            sage: G = graphics_array(L)
            sage: G.save(F, dpi=500, axes=False)

        TESTS::

            sage: graphics_array([]).save(F)
            sage: graphics_array([[]]).save(F)

        """
        from matplotlib import rcParams
        ext = os.path.splitext(filename)[1].lower()
        if ext in ['', '.sobj']:
            SageObject.save(self, filename)
        elif ext not in ALLOWED_EXTENSIONS:
            raise ValueError("allowed file extensions for images are '" +
                             "', '".join(ALLOWED_EXTENSIONS) + "'!")
        else:
            rc_backup = (rcParams['ps.useafm'], rcParams['pdf.use14corefonts'],
                         rcParams['text.usetex'])  # save the rcParams
            figure = self.matplotlib(figsize=figsize, **kwds)
            transparent = kwds.get('transparent',
                                   Graphics.SHOW_OPTIONS['transparent'])
            fig_tight = kwds.get('fig_tight',
                                 Graphics.SHOW_OPTIONS['fig_tight'])
            dpi = kwds.get('dpi', Graphics.SHOW_OPTIONS['dpi'])
            # One can output in PNG, PS, EPS, PDF, PGF, or SVG format,
            # depending on the file extension.
            # PGF is handled by a different backend
            if ext == '.pgf':
                from sage.misc.sage_ostools import have_program
                latex_implementations = [i for i in ["xelatex", "pdflatex",
                                                     "lualatex"]
                                         if have_program(i)]
                if not latex_implementations:
                    raise ValueError("Matplotlib requires either xelatex, "
                                     "lualatex, or pdflatex.")
                if latex_implementations[0] == "pdflatex":
                    # use pdflatex and set font encoding as per
                    # Matplotlib documentation:
                    # https://matplotlib.org/users/pgf.html#pgf-tutorial
                    pgf_options = {"pgf.texsystem": "pdflatex",
                                   "pgf.preamble": [
                                      r"\usepackage[utf8x]{inputenc}",
                                      r"\usepackage[T1]{fontenc}"
                                      ]}
                else:
                    pgf_options = {"pgf.texsystem": latex_implementations[0]}
                rcParams.update(pgf_options)
                from matplotlib.backends.backend_pgf import FigureCanvasPgf
                figure.set_canvas(FigureCanvasPgf(figure))
            # Matplotlib looks at the file extension to see what the renderer
            # should be. The default is FigureCanvasAgg for PNG's because this
            # is by far the most common type of files rendered, like in the
            # notebook, for example. If the file extension is not '.png', then
            # Matplotlib will handle it.
            else:
                from matplotlib.backends.backend_agg import FigureCanvasAgg
                figure.set_canvas(FigureCanvasAgg(figure))
            if isinstance(self, GraphicsArray):
                # tight_layout adjusts the *subplot* parameters so ticks aren't
                # cut off, etc.
                figure.tight_layout()
            opts = dict(dpi=dpi, transparent=transparent)
            if fig_tight is True:
                opts['bbox_inches'] = 'tight'
            figure.savefig(filename, **opts)
            # Restore the rcParams to the original, possibly user-set values
            (rcParams['ps.useafm'], rcParams['pdf.use14corefonts'],
             rcParams['text.usetex']) = rc_backup