How can you clear a Matplotlib text box that was previously drawn?
- Use
fig.texts
orax.texts
to print the list of all the titles present in thatfig/axes
. - Use
del
keyword of python to delete that specifictext
.
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.
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()