I'm trying to get the text handle from an object in matplotlib. The following is a somewhat rickety segue for the question of "Does anyone know how to find text on in the figure so that one may change the attributes of the text?" The origin of this issue is that the plot displays fine, but it needs some tweaks for the savefig command as the text is the same color as the shape. Digging into the library, the text is created as expected, with text:
cax.text(x, y, metadata['name'], color=color, size=fs, horizontalalignment='center', verticalalignment='center')
I have some shape objects in 'Z', and I plot them this way:
fig = plt.figure(1, figsize=(10,10), dpi=90)
cax = fig.add_subplot(111)
Z.plot(cax)
plt.axis('equal')
plt.draw()
The result is this image, and I want to get the text "idaho".
I picked "idaho" because it thought it'd be easy to find, but I've not been able to find it in the object.
The question: Does anyone know how to find text on in the figure so that one may change the attributes of the text?
I just cannot seem to figure it out from the documentation.
CodePudding user response:
All Artist
objects in matplotlib should have a findobj
method to recursively search its children for other Artists
that meet some criterion.
In this case you want to find all Text
objects that also have the text "idaho"
. So an example would look like this...
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.text(.5, .5, s='idaho')
from matplotlib.text import Text
matches = ax.findobj(
lambda artist: isinstance(artist, Text) and artist.get_text() == 'idaho'
)
print(matches) # Note that `ax.findobj` always returns a list
[Text(0.5, 0.5, 'idaho')]
Applied to your code, you should be able to do:
from matplotlib.text import Text
matches = cax.findobj(
lambda artist: isinstance(artist, Text) and artist.get_text() == 'idaho'
)
text_handle = matches[0]
For a complete example:
>>> fig, ax = plt.subplots()
>>> ax.text(.5, .5, s='idaho')
Text(0.5, 0.5, 'idaho')
>>> from matplotlib.text import Text
>>> text_handle = ax.findobj(lambda artist: isinstance(artist, Text) and artist.get_text() == 'idaho')[0]
>>> text_handle.set_text('IDAHO!!')
>>> plt.show()