예제 #1
0
def test_Bug_2543():
    # Test that it possible to add all values to itself / deepcopy
    # This was not possible because validate_bool_maybe_none did not
    # accept None as an argument.
    # https://github.com/matplotlib/matplotlib/issues/2543
    # We filter warnings at this stage since a number of them are raised
    # for deprecated rcparams as they should. We don't want these in the
    # printed in the test suite.
    with _api.suppress_matplotlib_deprecation_warning():
        with mpl.rc_context():
            _copy = mpl.rcParams.copy()
            for key in _copy:
                mpl.rcParams[key] = _copy[key]
        with mpl.rc_context():
            copy.deepcopy(mpl.rcParams)
        # real test is that this does not raise
        assert validate_bool_maybe_none(None) is None
        assert validate_bool_maybe_none("none") is None
        with pytest.raises(ValueError):
            validate_bool_maybe_none("blah")
    with pytest.raises(ValueError):
        validate_bool(None)
    with pytest.raises(ValueError):
        with mpl.rc_context():
            mpl.rcParams['svg.fonttype'] = True
def test_ParasiteAxesAuxTrans(parasite_cls):
    # Remove this line when this test image is regenerated.
    plt.rcParams['pcolormesh.snap'] = False

    data = np.ones((6, 6))
    data[2, 2] = 2
    data[0, :] = 0
    data[-2, :] = 0
    data[:, 0] = 0
    data[:, -2] = 0
    x = np.arange(6)
    y = np.arange(6)
    xx, yy = np.meshgrid(x, y)

    funcnames = ['pcolor', 'pcolormesh', 'contourf']

    fig = plt.figure()
    for i, name in enumerate(funcnames):

        ax1 = SubplotHost(fig, 1, 3, i+1)
        fig.add_subplot(ax1)

        with _api.suppress_matplotlib_deprecation_warning():
            ax2 = parasite_cls(ax1, IdentityTransform())
        ax1.parasites.append(ax2)
        if name.startswith('pcolor'):
            getattr(ax2, name)(xx, yy, data[:-1, :-1])
        else:
            getattr(ax2, name)(xx, yy, data)
        ax1.set_xlim((0, 5))
        ax1.set_ylim((0, 5))

    ax2.contour(xx, yy, data, colors='k')
예제 #3
0
def use(style):
    """
    Use Matplotlib style settings from a style specification.

    The style name of 'default' is reserved for reverting back to
    the default style settings.

    .. note::

       This updates the `.rcParams` with the settings from the style.
       `.rcParams` not defined in the style are kept.

    Parameters
    ----------
    style : str, dict, Path or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | Path | A path-like object which is a path to a style file.         |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str, Path or dict) applied from |
        |      | first to last in the list.                                  |
        +------+-------------------------------------------------------------+

    """
    style_alias = {'mpl20': 'default',
                   'mpl15': 'classic'}
    if isinstance(style, (str, Path)) or hasattr(style, 'keys'):
        # If name is a single str, Path or dict, make it a single element list.
        styles = [style]
    else:
        styles = style

    styles = (style_alias.get(s, s) if isinstance(s, str) else s
              for s in styles)
    for style in styles:
        if not isinstance(style, (str, Path)):
            _apply_style(style)
        elif style == 'default':
            # Deprecation warnings were already handled when creating
            # rcParamsDefault, no need to reemit them here.
            with _api.suppress_matplotlib_deprecation_warning():
                _apply_style(rcParamsDefault, warn=False)
        elif style in library:
            _apply_style(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                _apply_style(rc)
            except IOError as err:
                raise IOError(
                    "{!r} not found in the style library and input is not a "
                    "valid URL or path; see `style.available` for list of "
                    "available styles".format(style)) from err
예제 #4
0
def test_load_from_url():
    path = Path(__file__).parent / "baseline_images/pngsuite/basn3p04.png"
    url = ('file:' + ('///' if sys.platform == 'win32' else '') +
           path.resolve().as_posix())
    with _api.suppress_matplotlib_deprecation_warning():
        plt.imread(url)
    with urllib.request.urlopen(url) as file:
        plt.imread(file)
예제 #5
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')
                try:
                    import PyQt5
                # RuntimeError if PyQt4 already imported.
                except (ImportError, RuntimeError):
                    try:
                        import PySide2
                    except ImportError:
                        pytest.skip("Failed to import a Qt5 binding.")

        # 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."
            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)
def test_epoch2num():
    with _api.suppress_matplotlib_deprecation_warning():
        mdates._reset_epoch_test_example()
        mdates.set_epoch('0000-12-31')
        assert mdates.epoch2num(86400) == 719164.0
        assert mdates.num2epoch(719165.0) == 86400 * 2
        # set back to the default
        mdates._reset_epoch_test_example()
        mdates.set_epoch('1970-01-01T00:00:00')
        assert mdates.epoch2num(86400) == 1.0
        assert mdates.num2epoch(2.0) == 86400 * 2
예제 #7
0
def test_Bug_2543():
    # Test that it possible to add all values to itself / deepcopy
    # https://github.com/matplotlib/matplotlib/issues/2543
    # We filter warnings at this stage since a number of them are raised
    # for deprecated rcparams as they should. We don't want these in the
    # printed in the test suite.
    with _api.suppress_matplotlib_deprecation_warning():
        with mpl.rc_context():
            _copy = mpl.rcParams.copy()
            for key in _copy:
                mpl.rcParams[key] = _copy[key]
        with mpl.rc_context():
            copy.deepcopy(mpl.rcParams)
    with pytest.raises(ValueError):
        validate_bool(None)
    with pytest.raises(ValueError):
        with mpl.rc_context():
            mpl.rcParams['svg.fonttype'] = True
예제 #8
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)
예제 #9
0
def setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.

    try:
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    except locale.Error:
        try:
            locale.setlocale(locale.LC_ALL, 'English_United States.1252')
        except locale.Error:
            _log.warning("Could not set locale to English/United States. "
                         "Some date-related tests may fail.")

    mpl.use('Agg')

    with _api.suppress_matplotlib_deprecation_warning():
        mpl.rcdefaults()  # Start with all defaults

    # These settings *must* be hardcoded for running the comparison tests and
    # are not necessarily the default values as specified in rcsetup.py.
    set_font_settings_for_testing()
    set_reproducibility_for_testing()
예제 #10
0
def test_https_imread_smoketest():
    with _api.suppress_matplotlib_deprecation_warning():
        v = mimage.imread('https://matplotlib.org/1.5.0/_static/logo2.png')
예제 #11
0
def test_normalize_kwargs_pass(inp, expected, kwargs_to_norm):
    with _api.suppress_matplotlib_deprecation_warning():
        # No other warning should be emitted.
        assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm)
예제 #12
0
def test_normalize_kwargs_fail(inp, kwargs_to_norm):
    with pytest.raises(TypeError), \
         _api.suppress_matplotlib_deprecation_warning():
        cbook.normalize_kwargs(inp, **kwargs_to_norm)
예제 #13
0
def test_mathtext_to_png(tmpdir):
    with _api.suppress_matplotlib_deprecation_warning():
        mt = mathtext.MathTextParser('bitmap')
        mt.to_png(str(tmpdir.join('example.png')), '$x^2$')
        mt.to_png(io.BytesIO(), '$x^2$')
예제 #14
0
 def draw(self, renderer):
     from matplotlib import _api  # internal, *do not use*
     with _api.suppress_matplotlib_deprecation_warning():
         with plt.rc_context({"text.latex.preview": self.preview}):
             super().draw(renderer)
예제 #15
0
 def stride_is_deprecated(self):
     with _api.suppress_matplotlib_deprecation_warning():
         yield
예제 #16
0
def use(style):
    """
    Use Matplotlib style settings from a style specification.

    The style name of 'default' is reserved for reverting back to
    the default style settings.

    .. note::

       This updates the `.rcParams` with the settings from the style.
       `.rcParams` not defined in the style are kept.

    Parameters
    ----------
    style : str, dict, Path or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `.style.available`.      |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | Path | A path-like object which is a path to a style file.         |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str, Path or dict) applied from |
        |      | first to last in the list.                                  |
        +------+-------------------------------------------------------------+

    Notes
    -----
    The following `.rcParams` are not related to style and will be ignored if
    found in a style specification:

    %s
    """
    if isinstance(style, (str, Path)) or hasattr(style, 'keys'):
        # If name is a single str, Path or dict, make it a single element list.
        styles = [style]
    else:
        styles = style

    style_alias = {'mpl20': 'default', 'mpl15': 'classic'}

    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

    for style in map(fix_style, styles):
        if not isinstance(style, (str, Path)):
            _apply_style(style)
        elif style == 'default':
            # Deprecation warnings were already handled when creating
            # rcParamsDefault, no need to reemit them here.
            with _api.suppress_matplotlib_deprecation_warning():
                _apply_style(rcParamsDefault, warn=False)
        elif style in library:
            _apply_style(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                _apply_style(rc)
            except IOError as err:
                raise IOError(
                    "{!r} not found in the style library and input is not a "
                    "valid URL or path; see `style.available` for list of "
                    "available styles".format(style)) from err
예제 #17
0
from matplotlib import _api
from mpl_toolkits.axes_grid1.parasite_axes import (
    host_axes_class_factory, parasite_axes_class_factory,
    parasite_axes_auxtrans_class_factory, subplot_class_factory)
from mpl_toolkits.axisartist.axislines import Axes


ParasiteAxes = parasite_axes_class_factory(Axes)
HostAxes = host_axes_class_factory(Axes)
SubplotHost = subplot_class_factory(HostAxes)
with _api.suppress_matplotlib_deprecation_warning():
    ParasiteAxesAuxTrans = parasite_axes_auxtrans_class_factory(ParasiteAxes)