[英]Mask quiver plot with imshow in 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., 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的答案显示了这种方式,但是绘制多边形(可能仅是矩形)时,您无需费心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()
结果:
因此,要实现您的目标,只需创建一个黑色矩形即可“覆盖”绘图的各个部分。 另一种方法是使用蒙版数组首先仅显示颤动图和轮廓图的一部分: http : //matplotlib.org/examples/pylab_examples/contourf_demo.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.