Example #1
0
    def parse(self, s, dpi=72, prop=None, *, _force_standard_ps_fonts=False):
        """
        Parse the given math expression *s* at the given *dpi*.  If *prop* is
        provided, it is a `.FontProperties` object specifying the "default"
        font to use in the math expression, used for all non-math text.

        The results are cached, so multiple calls to `parse`
        with the same expression should be fast.
        """
        if _force_standard_ps_fonts:
            _api.warn_deprecated(
                "3.4",
                removal="3.5",
                message=(
                    "Mathtext using only standard PostScript fonts has "
                    "been likely to produce wrong output for a while, "
                    "has been deprecated in %(since)s and will be removed "
                    "in %(removal)s, after which ps.useafm will have no "
                    "effect on mathtext."
                )
            )

        # lru_cache can't decorate parse() directly because the ps.useafm and
        # mathtext.fontset rcParams also affect the parse (e.g. by affecting
        # the glyph metrics).
        return self._parse_cached(s, dpi, prop, _force_standard_ps_fonts)
Example #2
0
 def _warn_deprecated(self):
     _api.warn_deprecated(
         "3.3",
         message="The global colormaps dictionary is no longer "
         "considered public API.",
         alternative="Please use register_cmap() and get_cmap() to "
         "access the contents of the dictionary.")
Example #3
0
 def fix_style(s):
     if isinstance(s, str):
         s = style_alias.get(s, s)
         if s in [
                 "seaborn",
                 "seaborn-bright",
                 "seaborn-colorblind",
                 "seaborn-dark",
                 "seaborn-darkgrid",
                 "seaborn-dark-palette",
                 "seaborn-deep",
                 "seaborn-muted",
                 "seaborn-notebook",
                 "seaborn-paper",
                 "seaborn-pastel",
                 "seaborn-poster",
                 "seaborn-talk",
                 "seaborn-ticks",
                 "seaborn-white",
                 "seaborn-whitegrid",
         ]:
             _api.warn_deprecated(
                 "3.6",
                 message="The seaborn styles shipped by Matplotlib "
                 "are deprecated since %(since)s, as they no longer "
                 "correspond to the styles shipped by seaborn. However, "
                 "they will remain available as 'seaborn0.8-<style>'. "
                 "Alternatively, directly use the seaborn API instead.")
             s = s.replace("seaborn", "seaborn0.8")
     return s
Example #4
0
    def update_keymap(self, name, key, *args):
        """
        Set the keymap to associate with the specified tool.

        Parameters
        ----------
        name : str
            Name of the Tool.
        key : str or list of str
            Keys to associate with the tool.
        """
        if name not in self._tools:
            raise KeyError('%s not in Tools' % name)
        self._remove_keys(name)
        for key in [key, *args]:
            if isinstance(key, str) and validate_stringlist(key) != [key]:
                _api.warn_deprecated(
                    "3.3",
                    message="Passing a list of keys as a single "
                    "comma-separated string is deprecated since %(since)s and "
                    "support will be removed %(removal)s; pass keys as a list "
                    "of strings instead.")
                key = validate_stringlist(key)
            if isinstance(key, str):
                key = [key]
            for k in key:
                if k in self._keys:
                    _api.warn_external(
                        f'Key {k} changed from {self._keys[k]} to {name}')
                self._keys[k] = name
    def __init__(self, axes_divider, nx, ny, nx1=None, ny1=None):
        """
        Parameters
        ----------
        axes_divider : AxesDivider
        nx, nx1 : int
            Integers specifying the column-position of the
            cell. When *nx1* is None, a single *nx*-th column is
            specified. Otherwise location of columns spanning between *nx*
            to *nx1* (but excluding *nx1*-th column) is specified.
        ny, ny1 : int
            Same as *nx* and *nx1*, but for row positions.
        """
        self._axes_divider = axes_divider

        _xrefindex = axes_divider._xrefindex
        _yrefindex = axes_divider._yrefindex

        self._nx, self._ny = nx - _xrefindex, ny - _yrefindex

        if nx1 is None:
            _api.warn_deprecated(
                "3.5", message="Support for passing nx1=None to mean nx+1 is "
                "deprecated since %(since)s; in a future version, nx1=None "
                "will mean 'up to the last cell'.")
            nx1 = nx + 1
        if ny1 is None:
            _api.warn_deprecated(
                "3.5", message="Support for passing ny1=None to mean ny+1 is "
                "deprecated since %(since)s; in a future version, ny1=None "
                "will mean 'up to the last cell'.")
            ny1 = ny + 1

        self._nx1 = nx1 - _xrefindex
        self._ny1 = ny1 - _yrefindex
Example #6
0
def subplot_class_factory(axes_class=None):
    """
    Make a new class that inherits from `.SubplotBase` and the
    given axes_class (which is assumed to be a subclass of `.axes.Axes`).
    This is perhaps a little bit roundabout to make a new class on
    the fly like this, but it means that a new Subplot class does
    not have to be created for every type of Axes.
    """
    if axes_class is None:
        _api.warn_deprecated(
            "3.3",
            message="Support for passing None to subplot_class_factory "
            "is deprecated since %(since)s; explicitly pass the default Axes "
            "class instead. This will become an error %(removal)s.")
        axes_class = Axes

    try:
        # Avoid creating two different instances of GeoAxesSubplot...
        # Only a temporary backcompat fix.  This should be removed in
        # 3.4
        return next(cls for cls in SubplotBase.__subclasses__()
                    if cls.__bases__ == (SubplotBase, axes_class))
    except StopIteration:
        # if we have already wrapped this class, declare victory!
        if issubclass(axes_class, SubplotBase):
            return axes_class

        return type("%sSubplot" % axes_class.__name__,
                    (SubplotBase, axes_class), {'_axes_class': axes_class})
Example #7
0
    def get_text_width_height_descent(self, s, prop, ismath):
        # docstring inherited

        if ismath in ["TeX", "TeX!"]:
            if ismath == "TeX!":
                _api.warn_deprecated(
                    "3.3",
                    message="Support for ismath='TeX!' is deprecated "
                    "since %(since)s and will be removed %(removal)s; use "
                    "ismath='TeX' instead.")
            # todo: handle props
            texmanager = self.get_texmanager()
            fontsize = prop.get_size_in_points()
            w, h, d = texmanager.get_text_width_height_descent(s,
                                                               fontsize,
                                                               renderer=self)
            return w, h, d

        if ismath:
            ox, oy, width, height, descent, fonts, used_characters = \
                self.mathtext_parser.parse(s, self.dpi, prop)
            return width, height, descent

        flags = get_hinting_flag()
        font = self._get_agg_font(prop)
        font.set_text(s, 0.0, flags=flags)
        w, h = font.get_width_height()  # width and height of unrotated string
        d = font.get_descent()
        w /= 64.0  # convert from subpixels
        h /= 64.0
        d /= 64.0
        return w, h, d
Example #8
0
    def locate(self, nx, ny, nx1=None, ny1=None, axes=None, renderer=None):
        """
        Parameters
        ----------
        nx, nx1 : int
            Integers specifying the column-position of the
            cell. When *nx1* is None, a single *nx*-th column is
            specified. Otherwise location of columns spanning between *nx*
            to *nx1* (but excluding *nx1*-th column) is specified.
        ny, ny1 : int
            Same as *nx* and *nx1*, but for row positions.
        axes
        renderer
        """

        fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
        x, y, w, h = self.get_position_runtime(axes, renderer)

        hsizes = self.get_horizontal_sizes(renderer)
        vsizes = self.get_vertical_sizes(renderer)
        k_h = self._calc_k(hsizes, fig_w * w)
        k_v = self._calc_k(vsizes, fig_h * h)

        if self.get_aspect():
            k = min(k_h, k_v)
            ox = self._calc_offsets(hsizes, k)
            oy = self._calc_offsets(vsizes, k)

            ww = (ox[-1] - ox[0]) / fig_w
            hh = (oy[-1] - oy[0]) / fig_h
            pb = mtransforms.Bbox.from_bounds(x, y, w, h)
            pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
            x0, y0 = pb1.anchored(self.get_anchor(), pb).p0

        else:
            ox = self._calc_offsets(hsizes, k_h)
            oy = self._calc_offsets(vsizes, k_v)
            x0, y0 = x, y

        if nx1 is None:
            _api.warn_deprecated(
                "3.5",
                message="Support for passing nx1=None to mean nx+1 is "
                "deprecated since %(since)s; in a future version, nx1=None "
                "will mean 'up to the last cell'.")
            nx1 = nx + 1
        if ny1 is None:
            _api.warn_deprecated(
                "3.5",
                message="Support for passing ny1=None to mean ny+1 is "
                "deprecated since %(since)s; in a future version, ny1=None "
                "will mean 'up to the last cell'.")
            ny1 = ny + 1

        x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
        y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h

        return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
Example #9
0
    def print_jpg(self, filename_or_obj, *args, pil_kwargs=None, **kwargs):
        """
        Write the figure to a JPEG file.

        Parameters
        ----------
        filename_or_obj : str or path-like or file-like
            The file to write to.

        Other Parameters
        ----------------
        quality : int, default: :rc:`savefig.jpeg_quality`
            The image quality, on a scale from 1 (worst) to 95 (best).
            Values above 95 should be avoided; 100 disables portions of
            the JPEG compression algorithm, and results in large files
            with hardly any gain in image quality.  This parameter is
            deprecated.
        optimize : bool, default: False
            Whether the encoder should make an extra pass over the image
            in order to select optimal encoder settings.  This parameter is
            deprecated.
        progressive : bool, default: False
            Whether the image should be stored as a progressive JPEG file.
            This parameter is deprecated.
        pil_kwargs : dict, optional
            Additional keyword arguments that are passed to
            `PIL.Image.Image.save` when saving the figure.  These take
            precedence over *quality*, *optimize* and *progressive*.
        """
        # Remove transparency by alpha-blending on an assumed white background.
        r, g, b, a = mcolors.to_rgba(self.figure.get_facecolor())
        try:
            self.figure.set_facecolor(a * np.array([r, g, b]) + 1 - a)
            FigureCanvasAgg.draw(self)
        finally:
            self.figure.set_facecolor((r, g, b, a))
        if pil_kwargs is None:
            pil_kwargs = {}
        for k in ["quality", "optimize", "progressive"]:
            if k in kwargs:
                pil_kwargs.setdefault(k, kwargs.pop(k))
        if "quality" not in pil_kwargs:
            quality = pil_kwargs["quality"] = \
                dict.__getitem__(mpl.rcParams, "savefig.jpeg_quality")
            if quality not in [0, 75, 95]:  # default qualities.
                _api.warn_deprecated(
                    "3.3",
                    name="savefig.jpeg_quality",
                    obj_type="rcParam",
                    addendum="Set the quality using "
                    "`pil_kwargs={'quality': ...}`; the future default "
                    "quality will be 75, matching the default of Pillow and "
                    "libjpeg.")
        pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
        # Drop alpha channel now.
        return (Image.fromarray(np.asarray(self.buffer_rgba())[..., :3]).save(
            filename_or_obj, format='jpeg', **pil_kwargs))
Example #10
0
 def __init__(self, lines, arrows, **kwargs):
     if kwargs:
         _api.warn_deprecated(
             "3.3",
             message="Passing arbitrary keyword arguments to StreamplotSet "
             "is deprecated since %(since) and will become an "
             "error %(removal)s.")
     self.lines = lines
     self.arrows = arrows
Example #11
0
 def __getitem__(self, index):
     if index != 0:
         # Make HandlerLine2D return [self._legline] directly after
         # deprecation elapses.
         _api.warn_deprecated(
             "3.5", message="Access to the second element returned by "
             "HandlerLine2D is deprecated since %(since)s; it will be "
             "removed %(removal)s.")
     return [self._legline, self._legline][index]
Example #12
0
def find_tex_file(filename, format=None):
    try:
        return (_find_tex_file(filename, format)
                if format is not None else _find_tex_file(filename))
    except FileNotFoundError as exc:
        _api.warn_deprecated(
            "3.6",
            message=f"{exc.args[0]}; in the future, this will raise a "
            f"FileNotFoundError.")
        return ""
Example #13
0
def mpl_test_settings(request):
    from matplotlib.testing.decorators import _cleanup_cm

    with _cleanup_cm():

        backend = None
        backend_marker = request.node.get_closest_marker('backend')
        if backend_marker is not None:
            assert len(backend_marker.args) == 1, \
                "Marker 'backend' must specify 1 backend."
            backend, = backend_marker.args
            skip_on_importerror = backend_marker.kwargs.get(
                'skip_on_importerror', False)
            prev_backend = matplotlib.get_backend()

            # special case Qt backend importing to avoid conflicts
            if backend.lower().startswith('qt5'):
                if any(sys.modules.get(k) for k in ('PyQt4', 'PySide')):
                    pytest.skip('Qt4 binding already imported')

        # Default of cleanup and image_comparison too.
        style = ["classic", "_classic_test_patch"]
        style_marker = request.node.get_closest_marker('style')
        if style_marker is not None:
            assert len(style_marker.args) == 1, \
                "Marker 'style' must specify 1 style."
            _api.warn_deprecated("3.5",
                                 name="style",
                                 obj_type="pytest marker",
                                 alternative="@mpl.style.context(...)")
            style, = style_marker.args

        matplotlib.testing.setup()
        with _api.suppress_matplotlib_deprecation_warning():
            if backend is not None:
                # This import must come after setup() so it doesn't load the
                # default backend prematurely.
                import matplotlib.pyplot as plt
                try:
                    plt.switch_backend(backend)
                except ImportError as exc:
                    # Should only occur for the cairo backend tests, if neither
                    # pycairo nor cairocffi are installed.
                    if 'cairo' in backend.lower() or skip_on_importerror:
                        pytest.skip(
                            "Failed to switch to backend {} ({}).".format(
                                backend, exc))
                    else:
                        raise
            matplotlib.style.use(style)
        try:
            yield
        finally:
            if backend is not None:
                plt.switch_backend(prev_backend)
Example #14
0
    def __init__(self, size=None, weight='normal'):
        self._version = self.__version__

        self.__default_weight = weight
        self.default_size = size

        paths = [
            cbook._get_data_path('fonts', subdir)
            for subdir in ['ttf', 'afm', 'pdfcorefonts']
        ]
        #  Create list of font paths
        for pathname in ['TTFPATH', 'AFMPATH']:
            if pathname in os.environ:
                ttfpath = os.environ[pathname]
                if ttfpath.find(';') >= 0:  # win32 style
                    paths.extend(ttfpath.split(';'))
                elif ttfpath.find(':') >= 0:  # unix style
                    paths.extend(ttfpath.split(':'))
                else:
                    paths.append(ttfpath)
                _api.warn_deprecated("3.3",
                                     name=pathname,
                                     obj_type="environment variable",
                                     alternative="FontManager.addfont()")
        _log.debug('font search path %s', str(paths))
        #  Load TrueType fonts and create font dictionary.

        self.defaultFamily = {'ttf': 'DejaVu Sans', 'afm': 'Helvetica'}

        self.afmlist = []
        self.ttflist = []

        # Delay the warning by 5s.
        timer = Timer(
            5, lambda: _log.warning(
                'Matplotlib is building the font cache; this may take a moment.'
            ))
        timer.start()
        try:
            for fontext in ["afm", "ttf"]:
                for path in [
                        *findSystemFonts(paths, fontext=fontext),
                        *findSystemFonts(fontext=fontext)
                ]:
                    try:
                        self.addfont(path)
                    except OSError as exc:
                        _log.info("Failed to open font file %s: %s", path, exc)
                    except Exception as exc:
                        _log.info(
                            "Failed to extract font properties from %s: "
                            "%s", path, exc)
        finally:
            timer.cancel()
Example #15
0
def parasite_axes_class_factory(axes_class=None):
    if axes_class is None:
        _api.warn_deprecated(
            "3.3", message="Support for passing None to "
            "parasite_axes_class_factory is deprecated since %(since)s and "
            "will be removed %(removal)s; explicitly pass the default Axes "
            "class instead.")
        axes_class = Axes

    return type("%sParasite" % axes_class.__name__,
                (ParasiteAxesBase, axes_class), {})
Example #16
0
 def draw_path_collection(self, gc, master_transform, paths, all_transforms,
                          offsets, offsetTrans, facecolors, edgecolors,
                          linewidths, linestyles, antialiaseds, urls,
                          offset_position):
     if offset_position == "data":
         _api.warn_deprecated(
             "3.3", message="Support for offset_position='data' is "
             "deprecated since %(since)s and will be removed %(removal)s.")
     return self._renderer.draw_path_collection(
         gc, master_transform, paths, all_transforms, offsets, offsetTrans,
         facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls,
         offset_position)
Example #17
0
def _validate_hatch_pattern(hatch):
    valid_hatch_patterns = set(r'-+|/\xXoO.*')
    if hatch is not None:
        invalids = set(hatch).difference(valid_hatch_patterns)
        if invalids:
            valid = ''.join(sorted(valid_hatch_patterns))
            invalids = ''.join(sorted(invalids))
            _api.warn_deprecated(
                '3.4',
                message=f'hatch must consist of a string of "{valid}" or '
                        'None, but found the following invalid values '
                        f'"{invalids}". Passing invalid values is deprecated '
                        'since %(since)s and will become an error %(removal)s.'
            )
Example #18
0
def host_axes_class_factory(axes_class=None):
    if axes_class is None:
        _api.warn_deprecated(
            "3.3", message="Support for passing None to host_axes_class is "
            "deprecated since %(since)s and will be removed %(removed)s; "
            "explicitly pass the default Axes class instead.")
        axes_class = Axes

    def _get_base_axes(self):
        return axes_class

    return type("%sHostAxes" % axes_class.__name__,
                (HostAxesBase, axes_class),
                {'_get_base_axes': _get_base_axes})
Example #19
0
 def __init__(self, bitmap, dpi):
     """Initialise a wxWindows renderer instance."""
     _api.warn_deprecated(
         "2.0", name="wx", obj_type="backend", removal="the future",
         alternative="wxagg", addendum="See the Matplotlib usage FAQ for "
         "more info on backends.")
     super().__init__()
     _log.debug("%s - __init__()", type(self))
     self.width = bitmap.GetWidth()
     self.height = bitmap.GetHeight()
     self.bitmap = bitmap
     self.fontd = {}
     self.dpi = dpi
     self.gc = None
Example #20
0
 def validator(s):
     if (allow_none and
             (s is None or isinstance(s, str) and s.lower() == "none")):
         return None
     if cls is str and not isinstance(s, str):
         _api.warn_deprecated(
             "3.5", message="Support for setting an rcParam that expects a "
             "str value to a non-str value is deprecated since %(since)s "
             "and support will be removed %(removal)s.")
     try:
         return cls(s)
     except (TypeError, ValueError) as e:
         raise ValueError(
             f'Could not convert {s!r} to {cls.__name__}') from e
Example #21
0
    def new_vertical(self, size, pad=None, pack_start=False, **kwargs):
        """
        Add a new axes on the top (or bottom) side of the main axes.

        Parameters
        ----------
        size : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
            A height of the axes. If float or string is given, *from_any*
            function is used to create the size, with *ref_size* set to AxesX
            instance of the current axes.
        pad : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
            Pad between the axes. It takes same argument as *size*.
        pack_start : bool
            If False, the new axes is appended at the end
            of the list, i.e., it became the right-most axes. If True, it is
            inserted at the start of the list, and becomes the left-most axes.
        **kwargs
            All extra keywords arguments are passed to the created axes.
            If *axes_class* is given, the new axes will be created as an
            instance of the given class. Otherwise, the same class of the
            main axes will be used.
        """
        if pad is None:
            _api.warn_deprecated(
                "3.2",
                message="In a future version, 'pad' will default to "
                "rcParams['figure.subplot.hspace'].  Set pad=0 to keep the "
                "old behavior.")
        if pad:
            if not isinstance(pad, Size._Base):
                pad = Size.from_any(pad, fraction_ref=self._yref)
            if pack_start:
                self._vertical.insert(0, pad)
                self._yrefindex += 1
            else:
                self._vertical.append(pad)
        if not isinstance(size, Size._Base):
            size = Size.from_any(size, fraction_ref=self._yref)
        if pack_start:
            self._vertical.insert(0, size)
            self._yrefindex += 1
            locator = self.new_locator(nx=self._xrefindex, ny=0)
        else:
            self._vertical.append(size)
            locator = self.new_locator(nx=self._xrefindex,
                                       ny=len(self._vertical) - 1)
        ax = self._get_new_axes(**kwargs)
        ax.set_axes_locator(locator)
        return ax
Example #22
0
def parasite_axes_auxtrans_class_factory(axes_class=None):
    if axes_class is None:
        _api.warn_deprecated(
            "3.3", message="Support for passing None to "
            "parasite_axes_auxtrans_class_factory is deprecated since "
            "%(since)s and will be removed %(removal)s; explicitly pass the "
            "default ParasiteAxes class instead.")
        parasite_axes_class = ParasiteAxes
    elif not issubclass(axes_class, ParasiteAxesBase):
        parasite_axes_class = parasite_axes_class_factory(axes_class)
    else:
        parasite_axes_class = axes_class
    return type("%sParasiteAuxTrans" % parasite_axes_class.__name__,
                (ParasiteAxesAuxTransBase, parasite_axes_class),
                {'name': 'parasite_axes'})
Example #23
0
    def __init__(self, filename, *, keep_empty=True, metadata=None):
        """
        Create a new PdfPages object.

        Parameters
        ----------
        filename : str or path-like
            Plots using `PdfPages.savefig` will be written to a file at this
            location. Any older file with the same name is overwritten.

        keep_empty : bool, default: True
            If set to False, then empty pdf files will be deleted automatically
            when closed.

        metadata : dict, optional
            Information dictionary object (see PDF reference section 10.2.1
            'Document Information Dictionary'), e.g.:
            ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.

            The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
            'Creator', 'Producer', 'CreationDate', 'ModDate', and
            'Trapped'. Values have been predefined for 'Creator', 'Producer'
            and 'CreationDate'. They can be removed by setting them to `None`.

            Note that some versions of LaTeX engines may ignore the 'Producer'
            key and set it to themselves.
        """
        self._output_name = filename
        self._n_figures = 0
        self.keep_empty = keep_empty
        self._metadata = (metadata or {}).copy()
        if metadata:
            for key in metadata:
                canonical = {
                    'creationdate': 'CreationDate',
                    'moddate': 'ModDate',
                }.get(key.lower(),
                      key.lower().title())
                if canonical != key:
                    _api.warn_deprecated(
                        '3.3',
                        message='Support for setting PDF metadata keys '
                        'case-insensitively is deprecated since %(since)s and '
                        'will be removed %(removal)s; '
                        f'set {canonical} instead of {key}.')
                    self._metadata[canonical] = self._metadata.pop(key)
        self._info_dict = _create_pdf_info_dict('pgf', self._metadata)
        self._file = BytesIO()
Example #24
0
 def __call__(self, s):
     if self._deprecated_since:
         name, = (k for k, v in globals().items() if v is self)
         _api.warn_deprecated(self._deprecated_since,
                              name=name,
                              obj_type="function")
     if self.ignorecase:
         s = s.lower()
     if s in self.valid:
         return self.valid[s]
     msg = (f"{s!r} is not a valid value for {self.key}; supported values "
            f"are {[*self.valid.values()]}")
     if (isinstance(s, str) and (s.startswith('"') and s.endswith('"')
                                 or s.startswith("'") and s.endswith("'"))
             and s[1:-1] in self.valid):
         msg += "; remove quotes surrounding your string"
     raise ValueError(msg)
Example #25
0
def scale_factory(scale, axis, **kwargs):
    """
    Return a scale class by name.

    Parameters
    ----------
    scale : {%(names)s}
    axis : `matplotlib.axis.Axis`
    """
    if scale != scale.lower():
        _api.warn_deprecated(
            "3.5",
            message="Support for case-insensitive scales is deprecated "
            "since %(since)s and support will be removed %(removal)s.")
        scale = scale.lower()
    scale_cls = _api.check_getitem(_scale_mapping, scale=scale)
    return scale_cls(axis, **kwargs)
Example #26
0
 def locate(self, nx, ny, nx1=None, ny1=None, axes=None, renderer=None):
     # docstring inherited
     fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
     x, y, w, h = self.get_position_runtime(axes, renderer)
     summed_hs = self.get_vertical_sizes(renderer)
     equal_ws = self.get_horizontal_sizes(renderer)
     y0, x0, oy, ww = _locate(
         y, x, h, w, summed_hs, equal_ws, fig_h, fig_w, self.get_anchor())
     if ny1 is None:
         _api.warn_deprecated(
             "3.5", message="Support for passing ny1=None to mean ny+1 is "
             "deprecated since %(since)s; in a future version, ny1=None "
             "will mean 'up to the last cell'.")
         ny1 = ny + 1
     x1, w1 = x0, ww
     y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
     return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
Example #27
0
    def _from_subplot_args(figure, args):
        """
        Construct a `.SubplotSpec` from a parent `.Figure` and either

        - a `.SubplotSpec` -- returned as is;
        - one or three numbers -- a MATLAB-style subplot specifier.
        """
        message = ("Passing non-integers as three-element position "
                   "specification is deprecated since %(since)s and will be "
                   "removed %(removal)s.")
        if len(args) == 1:
            arg, = args
            if isinstance(arg, SubplotSpec):
                return arg
            else:
                if not isinstance(arg, Integral):
                    _api.warn_deprecated("3.3", message=message)
                    arg = str(arg)
                try:
                    rows, cols, num = map(int, str(arg))
                except ValueError:
                    raise ValueError(
                        f"Single argument to subplot must be a three-digit "
                        f"integer, not {arg}") from None
                i = j = num
        elif len(args) == 3:
            rows, cols, num = args
            if not (isinstance(rows, Integral) and isinstance(cols, Integral)):
                _api.warn_deprecated("3.3", message=message)
                rows, cols = map(int, [rows, cols])
            gs = GridSpec(rows, cols, figure=figure)
            if isinstance(num, tuple) and len(num) == 2:
                if not all(isinstance(n, Integral) for n in num):
                    _api.warn_deprecated("3.3", message=message)
                    i, j = map(int, num)
                else:
                    i, j = num
            else:
                if not isinstance(num, Integral):
                    _api.warn_deprecated("3.3", message=message)
                    num = int(num)
                if num < 1 or num > rows * cols:
                    raise ValueError(
                        f"num must be 1 <= num <= {rows*cols}, not {num}")
                i = j = num
        else:
            raise TypeError(f"subplot() takes 1 or 3 positional arguments but "
                            f"{len(args)} were given")

        gs = GridSpec._check_gridspec_exists(figure, rows, cols)
        if gs is None:
            gs = GridSpec(rows, cols, figure=figure)
        return gs[i - 1:j]
Example #28
0
    def convert(value, unit, axis):
        """
        Convert strings in *value* to floats using mapping information stored
        in the *unit* object.

        Parameters
        ----------
        value : str or iterable
            Value or list of values to be converted.
        unit : `.UnitData`
            An object mapping strings to integers.
        axis : `~matplotlib.axis.Axis`
            The axis on which the converted value is plotted.

            .. note:: *axis* is unused.

        Returns
        -------
        float or ndarray[float]
        """
        if unit is None:
            raise ValueError(
                'Missing category information for StrCategoryConverter; '
                'this might be caused by unintendedly mixing categorical and '
                'numeric data')
        StrCategoryConverter._validate_unit(unit)
        # dtype = object preserves numerical pass throughs
        values = np.atleast_1d(np.array(value, dtype=object))
        # pass through sequence of non binary numbers
        with _api.suppress_matplotlib_deprecation_warning():
            is_numlike = all(
                units.ConversionInterface.is_numlike(v)
                and not isinstance(v, (str, bytes)) for v in values)
        if is_numlike:
            _api.warn_deprecated(
                "3.5",
                message="Support for passing numbers through unit "
                "converters is deprecated since %(since)s and support will be "
                "removed %(removal)s; use Axis.convert_units instead.")
            return np.asarray(values, dtype=float)
        # force an update so it also does type checking
        unit.update(values)
        return np.vectorize(unit._mapping.__getitem__, otypes=[float])(values)
Example #29
0
    def __init__(self, num, fig, *, canvas_class=None):
        # On non-Windows platform, explicitly set the position - fix
        # positioning bug on some Linux platforms
        if wx.Platform == '__WXMSW__':
            pos = wx.DefaultPosition
        else:
            pos = wx.Point(20, 20)
        super().__init__(parent=None, id=-1, pos=pos)
        # Frame will be sized later by the Fit method
        _log.debug("%s - __init__()", type(self))
        _set_frame_icon(self)

        # The parameter will become required after the deprecation elapses.
        if canvas_class is not None:
            self.canvas = canvas_class(self, -1, fig)
        else:
            _api.warn_deprecated(
                "3.6",
                message="The canvas_class parameter will become "
                "required after the deprecation period starting in Matplotlib "
                "%(since)s elapses.")
            self.canvas = self.get_canvas(fig)

        # Auto-attaches itself to self.canvas.manager
        manager = FigureManagerWx(self.canvas, num, self)

        toolbar = self.canvas.manager.toolbar
        if toolbar is not None:
            self.SetToolBar(toolbar)

        # On Windows, canvas sizing must occur after toolbar addition;
        # otherwise the toolbar further resizes the canvas.
        w, h = map(math.ceil, fig.bbox.size)
        self.canvas.SetInitialSize(wx.Size(w, h))
        self.canvas.SetMinSize((2, 2))
        self.canvas.SetFocus()

        self.Fit()

        self.Bind(wx.EVT_CLOSE, self._on_close)
Example #30
0
    def _scale_norm(self, norm, vmin, vmax):
        """
        Helper for initial scaling.

        Used by public functions that create a ScalarMappable and support
        parameters *vmin*, *vmax* and *norm*. This makes sure that a *norm*
        will take precedence over *vmin*, *vmax*.

        Note that this method does not set the norm.
        """
        if vmin is not None or vmax is not None:
            self.set_clim(vmin, vmax)
            if norm is not None:
                _api.warn_deprecated(
                    "3.3",
                    message="Passing parameters norm and vmin/vmax "
                    "simultaneously is deprecated since %(since)s and "
                    "will become an error %(removal)s. Please pass "
                    "vmin/vmax directly to the norm when creating it.")

        # always resolve the autoscaling so we have concrete limits
        # rather than deferring to draw time.
        self.autoscale_None()