Skip to content

Commit

Permalink
FIX: allow reshape 2-D to return a bare 1-d list
Browse files Browse the repository at this point in the history
  • Loading branch information
jklymak committed Aug 29, 2018
1 parent ec18892 commit 9eac832
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
9 changes: 3 additions & 6 deletions lib/matplotlib/cbook/__init__.py
Expand Up @@ -1393,15 +1393,12 @@ def _reshape_2D(X, name):
"""
# Iterate over columns for ndarrays, over rows otherwise.
X = np.atleast_1d(X.T if isinstance(X, np.ndarray) else np.asarray(X))
if X.ndim == 1 and X.dtype.type != np.object_:
if X.ndim == 1 and not isinstance(X[0], collections.abc.Iterable):
# 1D array of scalars: directly return it.
return [X]
elif X.ndim in [1, 2]:
if hasattr(X[0], '__len__'):
# 2D array, or 1D array of iterables: flatten them first.
return [np.reshape(x, -1) for x in X]
else:
return [X]
# 2D array, or 1D array of iterables: flatten them first.
return [np.reshape(x, -1) for x in X]
else:
raise ValueError("{} must have 2 or fewer dimensions".format(name))

Expand Down
21 changes: 21 additions & 0 deletions lib/matplotlib/tests/test_cbook.py
Expand Up @@ -482,3 +482,24 @@ def test_flatiter():

assert 0 == next(it)
assert 1 == next(it)


def test_reshape2d():
class dummy():
pass
x = [dummy() for j in range(5)]
xnew = cbook._reshape_2D(x, 'x')
assert np.shape(xnew) == (1, 5)

x = np.arange(5)
xnew = cbook._reshape_2D(x, 'x')
assert np.shape(xnew) == (1, 5)

x = [[dummy() for j in range(5)] for i in range(3)]
xnew = cbook._reshape_2D(x, 'x')
assert np.shape(xnew) == (3, 5)

# this is strange behaviour, but...
x = np.random.rand(3, 5)
xnew = cbook._reshape_2D(x, 'x')
assert np.shape(xnew) == (5, 3)

0 comments on commit 9eac832

Please sign in to comment.