How can you clear a Matplotlib text box that was previously drawn?

Question:

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?

Asked By: Tim Carnahan

||

Answers:

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.

Answered By: Ajean

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()

Answered By: Riyan
  1. Use fig.texts or ax.texts to print the list of all the titles present in that fig/axes.
  2. Use 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.

Answered By: user41855

For those wondering how to do this with matplotlib.figure.Figure:

# gca = get current axis
del fig.gca().texts[0]
# Redraw
fig.canvas.draw_idle()
Answered By: Loggy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.