Background:
I am writing a Python script which creates an animation by updating a plt.figure every few milliseconds. I have noticed that the memory usage is increasing slowly but safely to indefinite.
After some debugging, I was able to reduce the problem to the following standalone example:
- Create a
Figure. - Connect to a mouse event, and call
ax.plot()in loop. Note that I callremove()immediately after, and asserting that there is exactly one artist to remove.
Running this example and clicking on plot area, memory usage will start climbing fast.
from matplotlib import pyplot as plt
class LeakTest:
def __init__(self):
self.fig, self.ax = plt.subplots()
self.cid = self.fig.canvas.callbacks.connect('button_press_event', self.start_leaking)
plt.show()
def start_leaking(self, event):
xarr, yarr = [1, 2, 3], [1, 4, 9] # zip(*arrow_pts)
for i in range(1000000):
print(i)
plot = self.ax.plot(xarr, yarr, color='red')
assert isinstance(plot, list)
assert len(plot) == 1
plot[0].remove()
if __name__ == '__main__':
tt = LeakTest()
Any idea why, or how to fix?
Edit:
- I am using Python 3.6 on Windows. PyCharm.
- matplotlib==3.3.4
- Default backend (Qt5Agg)
- Most important, I forgot - leaking only starts on mousee-press-event:
