Skip to content

Commit d0cdf97

Browse files
authored
Merge pull request #16361 from tacaswell/auto-backport-of-pr-16347-on-v2.2.x
Backport PR #16347: FIX: catch warnings from pandas in cbook._check_1d
2 parents 80c2280 + 9859fa2 commit d0cdf97

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

lib/matplotlib/cbook/__init__.py

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2066,11 +2066,33 @@ def _check_1d(x):
20662066
return np.atleast_1d(x)
20672067
else:
20682068
try:
2069-
ndim = x[:, None].ndim
2070-
# work around https://github.com/pandas-dev/pandas/issues/27775
2071-
# which mean the shape is not as expected. That this ever worked
2072-
# was an unintentional quirk of pandas the above line will raise
2073-
# an exception in the future.
2069+
# work around
2070+
# https://github.com/pandas-dev/pandas/issues/27775 which
2071+
# means the shape of multi-dimensional slicing is not as
2072+
# expected. That this ever worked was an unintentional
2073+
# quirk of pandas and will raise an exception in the
2074+
# future. This slicing warns in pandas >= 1.0rc0 via
2075+
# https://github.com/pandas-dev/pandas/pull/30588
2076+
#
2077+
# < 1.0rc0 : x[:, None].ndim == 1, no warning, custom type
2078+
# >= 1.0rc1 : x[:, None].ndim == 2, warns, numpy array
2079+
# future : x[:, None] -> raises
2080+
#
2081+
# This code should correctly identify and coerce to a
2082+
# numpy array all pandas versions.
2083+
with warnings.catch_warnings(record=True) as w:
2084+
warnings.filterwarnings("always",
2085+
category=DeprecationWarning,
2086+
module='pandas[.*]')
2087+
2088+
ndim = x[:, None].ndim
2089+
# we have definitely hit a pandas index or series object
2090+
# cast to a numpy array.
2091+
if len(w) > 0:
2092+
return np.asanyarray(x)
2093+
# We have likely hit a pandas object, or at least
2094+
# something where 2D slicing does not result in a 2D
2095+
# object.
20742096
if ndim < 2:
20752097
return np.atleast_1d(x)
20762098
return x

lib/matplotlib/tests/test_axes.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1472,6 +1472,15 @@ def test_hist_log():
14721472
ax.hist(data, fill=False, log=True)
14731473

14741474

1475+
def test_pandas_minimal_plot(pd):
1476+
# smoke test that series and index objcets do not warn
1477+
x = pd.Series([1, 2], dtype="float64")
1478+
plt.plot(x, x)
1479+
plt.plot(x.index, x)
1480+
plt.plot(x)
1481+
plt.plot(x.index)
1482+
1483+
14751484
@image_comparison(baseline_images=['hist_bar_empty'], remove_text=True,
14761485
extensions=['png'])
14771486
def test_hist_bar_empty():

0 commit comments

Comments
 (0)