Search code examples
matplotlibz-order

Streamplot always in foreground


When drawing an Artist with streamplot the second appears always in the foreground, although the drawing is made before the Artist:

enter image description here

The same done with pcolormesh looks like expected:

enter image description here

This is the code for both pictures:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

Y, X = np.mgrid[-3:3:100j, -3:3:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)

fig0, ax0 = plt.subplots()
working = False
if working:
    strm = ax0.pcolormesh(X, Y, U, cmap=plt.cm.autumn)
else:
    strm = ax0.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)
    fig0.colorbar(strm.lines)

#fig1, (ax1, ax2) = plt.subplots(ncols=2)
#ax1.streamplot(X, Y, U, V, density=[0.5, 1])
#
#lw = 5*speed / speed.max()
#ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)

e = Rectangle(xy=(0,0), width=1, height=1)
e.set_facecolor([0.9,0.9,0.9])
ax0.add_artist(e)

plt.show()

What can I do so the Artist overlays the streamplot?


Solution

  • You can change the z-order of Artists. For your example, try:

    e = Rectangle(xy=(0,0), width=1, height=1, zorder=10)
    

    According to a matplotlib example, the default z-order seems to be:

    • Patch / PatchCollection => 1
    • Line2D / LineCollection => 2
    • Text => 3

    This would explain why the streamplot (lines) would be drawn on top of the rectangle (a patch).