繁体   English   中英

如何使用 Matplotlib PolyCollection 绘制正方形?

[英]How to draw a square using Matplotlib PolyCollection?

我试图通过尝试一个非常小的例子来理解PolyCollection中的 PolyCollection 到 plot 一个正方形(我知道已经有补丁/艺术家)但我想了解我应该如何指定PolyCollection的顶点。

我尝试了以下方法:

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()

但我收到以下错误:

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,).

我的顶点已经有了形状(4,2)

我做错了什么?

verts应该是二维数组序列的列表。

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).

由于您只绘制一个正方形,因此您可以这样写:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM