Reputation: 241
I am trying to understand PolyCollection
from Matplotlib by trying a very minimal example to plot a square (I know there are already patches/artists for that) but I would like to understand how should I specify the vertices for PolyCollection
.
I have tried the following:
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
import numpy as np
verts = [[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]]
verts = np.array(verts)
print(verts.shape)
poly = PolyCollection(verts, facecolors = 'blue', edgecolors='k', linewidth=1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.add_collection(poly)
plt.show()
but I get the following error:
main.py 9 <module>
poly = PolyCollection(verts, facecolors = 'blue', edgecolors='k', linewidth=1)
collections.py 1189 __init__
self.set_verts(verts, closed)
collections.py 1234 set_verts
self._paths.append(mpath.Path(xy, closed=True))
path.py 130 __init__
_api.check_shape((None, 2), vertices=vertices)
__init__.py 164 check_shape
raise ValueError(
ValueError:
'vertices' must be 2D with shape (M, 2). Your input has shape (3,).
My vertices have already the shape (4,2)
.
What I am doing wrong?
Upvotes: 0
Views: 821
Reputation: 38952
verts
should be a list of 2D array-like sequences.
PolyCollection?
Init signature: PolyCollection(verts, sizes=None, closed=True, **kwargs)
Docstring: Base class for collections that have an array of sizes.
Init docstring:
Parameters
----------
verts : list of array-like
The sequence of polygons [*verts0*, *verts1*, ...] where each
element *verts_i* defines the vertices of polygon *i* as a 2D
array-like of shape (M, 2).
Since you are plotting just one square, you can write:
square_verts = [[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]]
poly = PolyCollection([square_verts], facecolors = 'blue', edgecolors='k', linewidth=1)
Upvotes: 2