在 matplotlib 中使用 imshow 屏蔽颤动图
Mask quiver plot with imshow in matplotlib
我有一个箭袋图,下面有一个等高线图。这些都是由二维数组定义的。
我希望能够 "draw" 图形顶部的对象,例如将 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 的代码Path Tutorial
@Favo 的回答指明了方向,但要绘制多边形(并且可能只绘制矩形),您无需费心 Path
。 Matplotlib 会为你做到这一点。只需使用 Polygon
或 Rectangle
类:
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()
结果:
因此,为了实现您的目标,只需在地块的 "cover" 部分创建一个黑色矩形。另一种方法是首先使用掩码数组仅显示颤抖图和等高线图的一部分:
http://matplotlib.org/examples/pylab_examples/contourf_demo.html
我有一个箭袋图,下面有一个等高线图。这些都是由二维数组定义的。
我希望能够 "draw" 图形顶部的对象,例如将 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 的代码Path Tutorial
@Favo 的回答指明了方向,但要绘制多边形(并且可能只绘制矩形),您无需费心 Path
。 Matplotlib 会为你做到这一点。只需使用 Polygon
或 Rectangle
类:
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()
结果:
因此,为了实现您的目标,只需在地块的 "cover" 部分创建一个黑色矩形。另一种方法是首先使用掩码数组仅显示颤抖图和等高线图的一部分: http://matplotlib.org/examples/pylab_examples/contourf_demo.html