Jacky Liu
Jacky Liu

Reputation: 45

Matplotlib - How to set Text below other objects when they overlap?

when using matplotlib, how can I set the text to be below other objects, like Rectangles, LineCollections, etc ? Or more generally, how does matplotlib decide the order the objects will appear when they overlap each other? Unlike with grids, there's no function like Axes.set_textbelow() to use, I also googled this subject but got no satisfying result.

Below is the stock chart I draw with matplotlib. Note the volume section, I want to set the notes(white text) to be below the volume bars where they overlap. The notes are Text objects drawn with Axes.text(), the volume bars are LineCollection objects drawn with Axes.vlines().

stock chart I draw with matplotlib

Upvotes: 2

Views: 1113

Answers (1)

Daan
Daan

Reputation: 2059

You are probably looking for zorder:

from pylab import *

fig = figure(1)
fig.clf()
ax = subplot(111)
rect = matplotlib.patches.Rectangle((0.2,0.2), 0.3, 0.3, fc = '0.5', ec = '0.0')
ax.add_patch(rect)
ax.text(.4, .4, "Help me, there is a rectangle stuck under me!")

fig = figure(2)
fig.clf()
ax = subplot(111)
rect = matplotlib.patches.Rectangle((0.2,0.2), 0.3, 0.3, fc = '0.5', ec = '0.0')
ax.add_patch(rect)
ax.text(.4, .4, "Help me, I'm stuck under a rectangle!", zorder = -1)

show()

Upvotes: 3

Related Questions