Note
Click here to download the full example code
Zorder DemoΒΆ
The drawing order of artists is determined by their zorder
attribute, which
is a floating point number. Artists with higher zorder
are drawn on top.
You can change the order for individual artists by setting their zorder
.
The default value depends on the type of the Artist:
Artist | Z-order |
---|---|
Images (AxesImage , FigureImage , BboxImage ) |
0 |
Patch , PatchCollection |
1 |
Line2D , LineCollection (including minor ticks, grid lines) |
2 |
Major ticks | 2.01 |
Text (including axes labels and titles) |
3 |
Legend |
5 |
Any call to a plotting method can set a value for the zorder of that particular item explicitly.
Note
set_axisbelow
and rcParams["axes.axisbelow"]
(default: 'line') can further modify the
zorder of ticks and grid lines.
The following example contains a Line2D
created by plot()
and the dots (a PatchCollection
) created by scatter()
.
Hence, by default the dots are below the line (first subplot).
In the second subplot, the zorder
is set explicitly to move the dots
on top of the line.

Many functions that create a visible object accepts a zorder
parameter.
Alternatively, you can call set_order()
on the created object later.
x = np.linspace(0, 7.5, 100)
plt.rcParams['lines.linewidth'] = 5
plt.figure()
plt.plot(x, np.sin(x), label='zorder=2', zorder=2) # bottom
plt.plot(x, np.sin(x+0.5), label='zorder=3', zorder=3)
plt.axhline(0, label='zorder=2.5', color='lightgrey', zorder=2.5)
plt.title('Custom order of elements')
l = plt.legend(loc='upper right')
l.set_zorder(2.5) # legend between blue and orange line
plt.show()

Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery