From ff8b1a943d61b22ccad2e5ffd59893f0fc4fba69 Mon Sep 17 00:00:00 2001 From: Jody Klymak Date: Tue, 28 Jan 2020 15:20:18 -0800 Subject: [PATCH] Backport PR #16347: FIX: catch warnings from pandas in cbook._check_1d --- lib/matplotlib/cbook/__init__.py | 32 ++++++++++++++++++++++++++----- lib/matplotlib/tests/test_axes.py | 9 +++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index acf6b8fe54ae..d6fcf855f487 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -1326,11 +1326,33 @@ def _check_1d(x): return np.atleast_1d(x) else: try: - ndim = x[:, None].ndim - # work around https://github.com/pandas-dev/pandas/issues/27775 - # which mean the shape is not as expected. That this ever worked - # was an unintentional quirk of pandas the above line will raise - # an exception in the future. + # work around + # https://github.com/pandas-dev/pandas/issues/27775 which + # means the shape of multi-dimensional slicing is not as + # expected. That this ever worked was an unintentional + # quirk of pandas and will raise an exception in the + # future. This slicing warns in pandas >= 1.0rc0 via + # https://github.com/pandas-dev/pandas/pull/30588 + # + # < 1.0rc0 : x[:, None].ndim == 1, no warning, custom type + # >= 1.0rc1 : x[:, None].ndim == 2, warns, numpy array + # future : x[:, None] -> raises + # + # This code should correctly identify and coerce to a + # numpy array all pandas versions. + with warnings.catch_warnings(record=True) as w: + warnings.filterwarnings("always", + category=DeprecationWarning, + module='pandas[.*]') + + ndim = x[:, None].ndim + # we have definitely hit a pandas index or series object + # cast to a numpy array. + if len(w) > 0: + return np.asanyarray(x) + # We have likely hit a pandas object, or at least + # something where 2D slicing does not result in a 2D + # object. if ndim < 2: return np.atleast_1d(x) return x diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 290dfa64664b..4bf3e8724745 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -1669,6 +1669,15 @@ def test_bar_pandas_indexed(pd): ax.bar(df.x, 1., width=df.width) +def test_pandas_minimal_plot(pd): + # smoke test that series and index objcets do not warn + x = pd.Series([1, 2], dtype="float64") + plt.plot(x, x) + plt.plot(x.index, x) + plt.plot(x) + plt.plot(x.index) + + @image_comparison(['hist_log'], remove_text=True) def test_hist_log(): data0 = np.linspace(0, 1, 200)**3