Skip to content

Commit a7501f9

Browse files
authored
Merge pull request #16347 from tacaswell/fix_pandas_index_deprecation
FIX: catch warnings from pandas in cbook._check_1d
2 parents cc96303 + 77e7b31 commit a7501f9

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
@@ -1367,11 +1367,33 @@ def _check_1d(x):
13671367
return np.atleast_1d(x)
13681368
else:
13691369
try:
1370-
ndim = x[:, None].ndim
1371-
# work around https://github.com/pandas-dev/pandas/issues/27775
1372-
# which mean the shape is not as expected. That this ever worked
1373-
# was an unintentional quirk of pandas the above line will raise
1374-
# an exception in the future.
1370+
# work around
1371+
# https://github.com/pandas-dev/pandas/issues/27775 which
1372+
# means the shape of multi-dimensional slicing is not as
1373+
# expected. That this ever worked was an unintentional
1374+
# quirk of pandas and will raise an exception in the
1375+
# future. This slicing warns in pandas >= 1.0rc0 via
1376+
# https://github.com/pandas-dev/pandas/pull/30588
1377+
#
1378+
# < 1.0rc0 : x[:, None].ndim == 1, no warning, custom type
1379+
# >= 1.0rc1 : x[:, None].ndim == 2, warns, numpy array
1380+
# future : x[:, None] -> raises
1381+
#
1382+
# This code should correctly identify and coerce to a
1383+
# numpy array all pandas versions.
1384+
with warnings.catch_warnings(record=True) as w:
1385+
warnings.filterwarnings("always",
1386+
category=DeprecationWarning,
1387+
module='pandas[.*]')
1388+
1389+
ndim = x[:, None].ndim
1390+
# we have definitely hit a pandas index or series object
1391+
# cast to a numpy array.
1392+
if len(w) > 0:
1393+
return np.asanyarray(x)
1394+
# We have likely hit a pandas object, or at least
1395+
# something where 2D slicing does not result in a 2D
1396+
# object.
13751397
if ndim < 2:
13761398
return np.atleast_1d(x)
13771399
return x

lib/matplotlib/tests/test_axes.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1695,6 +1695,15 @@ def test_bar_pandas_indexed(pd):
16951695
ax.bar(df.x, 1., width=df.width)
16961696

16971697

1698+
def test_pandas_minimal_plot(pd):
1699+
# smoke test that series and index objcets do not warn
1700+
x = pd.Series([1, 2], dtype="float64")
1701+
plt.plot(x, x)
1702+
plt.plot(x.index, x)
1703+
plt.plot(x)
1704+
plt.plot(x.index)
1705+
1706+
16981707
@image_comparison(['hist_log'], remove_text=True)
16991708
def test_hist_log():
17001709
data0 = np.linspace(0, 1, 200)**3

0 commit comments

Comments
 (0)