Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python matplotlib中带imshow的遮罩颤动图_Python_Matplotlib - Fatal编程技术网

Python matplotlib中带imshow的遮罩颤动图

Python matplotlib中带imshow的遮罩颤动图,python,matplotlib,Python,Matplotlib,我有一个箭袋图,下面有一个等高线图。它们都是由二维数组定义的 我希望能够在图形顶部“绘制”对象,例如,在绘图的某处覆盖一个10x10的黑色正方形。对象应为黑色,图形的其余部分不应隐藏 plt.contourf(X, Y, h) plt.colorbar() plt.quiver(X[::2,::2], Y[::2,::2], u[::2,::2], v[::2,::2]) plt.show() 做这件事的好方法是什么?如果你所说的对象是指多边形,你可以这样做 verts = [ (0.

我有一个箭袋图,下面有一个等高线图。它们都是由二维数组定义的

我希望能够在图形顶部“绘制”对象,例如,在绘图的某处覆盖一个10x10的黑色正方形。对象应为黑色,图形的其余部分不应隐藏

plt.contourf(X, Y, h)
plt.colorbar()
plt.quiver(X[::2,::2], Y[::2,::2], u[::2,::2], v[::2,::2])
plt.show()

做这件事的好方法是什么?

如果你所说的对象是指多边形,你可以这样做

verts = [
    (0., 0.), # left, bottom
    (0., 1.), # left, top
    (1., 1.), # right, top
    (1., 0.), # right, bottom
    (0., 0.), # ignored
    ]

codes = [Path.MOVETO,
         Path.LINETO,
         Path.LINETO,
         Path.LINETO,
         Path.CLOSEPOLY,
         ]

path = Path(verts, codes)

fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='black')
ax.add_patch(patch)

ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
plt.show()

Matplotlib中的代码

@Favo的答案说明了方法,但是要绘制多边形(可能只有矩形),您不需要费心于路径。Matplotlib将为您完成这项工作。只需使用
多边形
矩形
类:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1,1)

# Directly instantiate polygons
coordinates = [[0.5,0.6],[0.5,0.7],[0.55,0.75],[0.6,0.7],[0.6,0.6]]
poly = plt.Polygon(coordinates, facecolor='black')
ax.add_patch(poly)

# If you just need a Rectangle, then there is a class for that too
rect = plt.Rectangle([0.2,0.2], 0.1, 0.1, facecolor='red')
ax.add_patch(rect)

plt.show()
结果:

因此,为了实现你的目标,只需创建一个黑色矩形来“覆盖”部分情节。另一种方法是首先使用遮罩阵列仅显示箭袋和等高线图的一部分: