Derek Eden
Derek Eden

Reputation: 4618

getting ValueError: 'vertices' must be a 2D list or array with shape Nx2, when it is Nx2?

I am trying to plot a mesh using node coordinates and connectivity as outlined here:

link

I have a list of node coordinates stored in a numpy array (x y and z coordinates)

I define x and y as:

x = coords[:,0]
y = coords[:,1]

I have the node connectivity in a numpy array connectivity, it has the id numbers of the coordinates that connect together

then, following their example, do the following:

xy = np.c_[x,y]
verts= xy[connectivity]
pc = matplotlib.collections.PolyCollection(verts)

and I get this error:

  File "C:\Users\deden\AppData\Local\Continuum\anaconda3\envs\dhi\lib\site-packages\matplotlib\path.py", line 130, in __init__
    "'vertices' must be a 2D list or array with shape Nx2")

ValueError: 'vertices' must be a 2D list or array with shape Nx2

to check:

xy.shape[1] is 2 and xy.ndim is 2

the line 130 in the file in the traceback is:

vertices = _to_unmasked_float_array(vertices)
if vertices.ndim != 2 or vertices.shape[1] != 2:
    raise ValueError(
        "'vertices' must be a 2D list or array with shape Nx2")

and _to_unmasked_float_array(vertices) calls:

def _to_unmasked_float_array(x):
    """
    Convert a sequence to a float array; if input was a masked array, masked
    values are converted to nans.
    """
    if hasattr(x, 'mask'):
        return np.ma.asarray(x, float).filled(np.nan)
    else:
        return np.asarray(x, float)

I don't understand why I am getting this error msg if verts.shape[1] and verts.ndim = 2

also np.asarray(verts, float).shape[1] and np.asarray(verts, float).ndim is also 2

what the heck is going on? am I missing something? would really appreciate anyones help

also..

verts.shape

returns

(181660, 2)

Upvotes: 1

Views: 9631

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

Since you want to draw a collection, you want verts to be a list of vertices per polygon. More technically spoken, as the documentation puts it,

verts is a sequence of ( verts0, verts1, ...) where verts_i is a sequence of xy tuples of vertices, or an equivalent numpy array of shape (nv, 2).

Hence, if your collection only has a single polygon, it still needs to be a list with a single entry. In your case

PolyCollection([verts])

Upvotes: 3

Related Questions