Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 334
Tim Carnahan Avatar asked Sep 23 '14 21:09

Tim Carnahan


People also ask

What is the command to clear all existing plots?

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.


3 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.

like image 133
Ajean Avatar answered Oct 20 '22 16:10

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

like image 22
Riyan Avatar answered Oct 20 '22 15:10

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.

like image 27
user41855 Avatar answered Oct 20 '22 14:10

user41855