Gus
Gus

Reputation: 1923

Mask quiver plot with imshow in matplotlib

I have a quiver plot I am showing with a contour plot underneath it. These are both defined by 2-D arrays.

I want to be able to "draw" objects on top of the graph, for example overlay a 10x10 black square somewhere onto the plot. The object should be black and the rest of the graph shouldn't be hidden.

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

What is a good way to do this?

Upvotes: 0

Views: 1312

Answers (2)

hitzg
hitzg

Reputation: 12701

@Favo's answer shows the way, but to draw polygons (and potentially only rectangles), you don't need to bother with Path. Matplotlib will do that for you. Just use the Polygon or Rectangle classes:

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

Result: enter image description here

So to achieve your goal just create a black rectangle to "cover" parts of your plot. Another way would be to use masked arrays to only show parts of the quiver and contour plots in the first place: http://matplotlib.org/examples/pylab_examples/contourf_demo.html

Upvotes: 1

Favo
Favo

Reputation: 838

If by objects you mean polygons, you can do this.

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

Code from Matplotlib Path Tutorial

Upvotes: 1

Related Questions