Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 522
Mastiff Avatar asked Dec 09 '25 11:12

Mastiff


1 Answers

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.

like image 77
Roy Avatar answered Dec 12 '25 01:12

Roy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!