Mastiff
Mastiff

Reputation: 2240

Matplotlib: How to clear a plot element using its handle

I don't understand why this is so hard, but I can't figure out how to do it. If I have multiple lines or points plotted and want to clear one of them, how is that done? Other posts point to remove(), but this is not working in my case. See example:

Python 2.7.5 (default, Apr  2 2020, 13:16:51) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> 
>>> plt.ion()
>>> x = np.arange(100.) / 99
>>> y = np.sin(x)
>>> fig, ax = plt.subplots()
>>> h = ax.plot(x, y)
>>> h.remove()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly one argument (0 given)

Upvotes: 2

Views: 1310

Answers (1)

Roy
Roy

Reputation: 11

I think JohanC's answer is indeed correct.
You can simply try putting a print(h) just before h.remove() line. We will notice a list object being returned. However, if you use h = ax.plot(x, y) instead and then use print(h), we will see only one object like Line2D being returned (not a list) and h.remove() should work.

Upvotes: 1

Related Questions