How can you clear a Matplotlib textbox that was previously drawn?

To clear a Matplotlib textbox that was previously drawn, you can use the remove() method on the text object. This is useful when you need to dynamically update or clear text elements from your plots.

Basic Text Removal

When you create text in Matplotlib, it returns a text artist object that you can later remove using the remove() method.

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create plot
fig, ax = plt.subplots()
x = np.linspace(-10, 10, 100)
y = np.sin(x)
ax.plot(x, y)

# Add text and store the reference
text = fig.text(0.5, 0.96, "$y=sin(x)$", ha='center')

plt.show()

Clearing the Text

To remove the text, simply call the remove() method on the text object ?

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()
x = np.linspace(-10, 10, 100)
y = np.sin(x)
ax.plot(x, y)

# Add text
text = fig.text(0.5, 0.96, "$y=sin(x)$", ha='center')

# Remove the text
text.remove()

plt.show()

Multiple Text Elements

You can also remove multiple text elements by storing them in a list ?

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = np.linspace(-5, 5, 100)
y = x**2

ax.plot(x, y)

# Add multiple text elements
texts = []
texts.append(ax.text(0, 20, "Peak", ha='center'))
texts.append(ax.text(-3, 5, "Left", ha='center'))
texts.append(ax.text(3, 5, "Right", ha='center'))

# Remove all text elements
for text in texts:
    text.remove()

plt.show()

Key Points

  • Always store the text object reference when creating text
  • Use text.remove() to clear the text from the plot
  • The remove() method works for any Matplotlib artist object
  • You can remove multiple text elements by iterating through a list

Conclusion

Use the remove() method on text objects to clear Matplotlib textboxes. Always store the text reference when creating it so you can remove it later when needed.

Updated on: 2026-03-25T22:54:12+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements