I’m searching for a way to extract all text elements from a matplotlibfigure including their position, style, alignment etc. Calling the findobj(matplotlib.text.Text) method of a figure does that job exactly. However, I get some weird duplicates for all the tick labels and I don’t know how to handle them.
For example, use findobj for printing all Text elements of an axis:
import matplotlib
import pylab as p
p.plot([1,2,3])
p.xticks([1],["tick"])
ax = p.gca()
fig = p.gcf()
p.draw()
def print_texts(artist):
for t in artist.findobj(matplotlib.text.Text):
if t.get_visible() and t.get_text():
print " %r @ %s" % (t.get_text(), t.get_position())
print "X-Axis Text Elements:"
print_texts(ax.xaxis)
print "Y-Axis Text Elements:"
print_texts(ax.yaxis)
Result:
X-Axis Text Elements:
'tick' @ (1.0, 0.0)
'tick' @ (0.0, 1.0)
Y-Axis Text Elements:
u'1.0' @ (0.0, 1.0)
u'1.0' @ (1.0, 0.0)
u'1.5' @ (0.0, 1.5)
u'1.5' @ (1.0, 0.0)
u'2.0' @ (0.0, 2.0)
u'2.0' @ (1.0, 0.0)
u'2.5' @ (0.0, 2.5)
u'2.5' @ (1.0, 0.0)
u'3.0' @ (0.0, 3.0)
u'3.0' @ (1.0, 0.0)
Note that all tick labels have duplicates positioned at the end of the axis. Why? How to filter them out from a list of Text elements? Their get_visible() attribute is True.
Another thing is that I first have to do call draw() in order to update/generate the ticks. How do I force an update of the tick labels? matplotlib.colorbar.Colorbar seems to have a update_ticks() method, but I can’t find something similar for ticks on the axes.
I also tried writing a custum backend and fetch all the texts from the draw_text()
method of the renderer. In contrast to the documentation draw_text() does
not receive a matplotlib.text.Text instance with all the necessary
information but only a simple string and a pre-layouted position.
The answer to this problem was given in the matplotlib mailing list. The Tick object always creates two text labels, one for the left/bottom and one for the right/top. When a Tick artist is drawn its
label1Onandlabel2Onattributes define which of the two child text labels receive thedraw()call. Both of them remain in the visible state however.So before iterating through all the text elements of a figure, I hide those labels that are not supposed to be seen: