I can make text boxes in matplotlib fine. But I dont see how to remove them from a rendered plot? There seems to be no figure.text.clear() or figure.text(visible=False) after you draw a text box? How is this done? and unlike legends, you seem to be unable to make them draggable?
plt. clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.
Text boxes are artists. As such, you should be able to do lots of things with them if you keep a reference to them. Hence, in any plotting code, instead of
fig.text(0, 0, 'My text')
you can do
textvar = fig.text(0, 0, 'My text')
If you've lost the references, though, all the text objects can be found in the texts
attribute:
fig.texts # is a list of Text objects
In version 1.3.1, doing textvar.remove()
generates a NotImplementedError (apparently fixed in 1.4). However, you can get around that to some degree by setting the visibility to False.
for txt in fig.texts:
txt.set_visible(False)
will make all your text boxes disappear.
I tried to remove text()
by using Artist.remove()
and it works fine.
We can also show/hide artist by using Artist.set_visible()
import matplotlib.pyplot as plt
from matplotlib.artist import Artist
fig, ax = plt.subplots()
frame = plt.text(0.6, 0.7, "hello world!", size=50,
ha="center", va="center",
)
# To hide the artist
Artist.set_visible(frame, False)
# To show the artist
Artist.set_visible(frame, True)
# To remove the artist
Artist.remove(frame)
plt.show()
fig.texts
or ax.texts
to print the list of all the titles present in that fig/axes
.del
keyword of python to delete that specific text
.Consider the following example:
print(fig.texts)
Ouput:
[Text(-0.3, 5, 'Features data distribution'),
Text(-0.3, 4.5, 'Secondary title')]
Say you have to delete 'Secondary title'
del fig.texts[1]
print(fig.texts)
Output:
[Text(-0.3, 5, 'Features data distribution')]
In the figure that title would be deleted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With