Matplotlib and Pyplot.close() not releasing memory? - backend related Qt4Agg

最后都变了- 提交于 2019-12-04 23:37:29

I think the reason it is doing this is because as it goes through all of the different graphs it then runs out of memory probably because it isn't releasing it properly.

Why don't you try creating about 3 or so programs each of which do a few graphs instead of one program doing all the graphs:

Program 1: Graphs 1-8

Program 2: Graphs 9-16

Program 3: Graphs 17-25

Hope this helps @FakeDIY : )

I run into a very similar problem once. I assume matplotlib keeps references for each plots internally. Given the following code, creating three separate figures:

import matplotlib.pyplot as plt
import numpy as np

# block 1
f, ax = plt.subplots(1)
plt.plot(np.arange(10), np.random.random(10))
plt.title("first")
print 'first', sys.getrefcount(f), sys.getrefcount(ax)

# bock 2
f, ax = plt.subplots(1)
plt.plot(np.arange(10), np.random.random(10)+1)
plt.title("second")
print 'second', sys.getrefcount(f), sys.getrefcount(ax)

# block 3
f, ax = plt.subplots(1)
plt.plot(np.arange(10), np.random.random(10)+2)
plt.title("third")
print 'third', sys.getrefcount(f), sys.getrefcount(ax)

plt.show()

print 'after show', sys.getrefcount(f), sys.getrefcount(ax)

Output:

first 69 26
second 69 26
third 69 26
after show 147 39

This is counter intuitive, because we redefined f and ax several times. With every block, we created a new figure, which can be referenced via plt. Creating another figure changes the topmost references accessible by plt. But there must be some internal reference, which allows plt.show() to show all figures. Those references seem to be persistent and thus the figures won't be collected by the gc.

The workaround I settled with, was changing the data of the plot. In hindsight it was a better approach anyway:

plt.ion()
f, ax = plt.subplots(1)
line = ax.plot(np.arange(10), np.random.random(10))[0]
plt.title('first')
plt.show()

for i, s in [(2, 'second'), (3, 'third')]:
    x = np.arange(10)
    y = np.random.random(10)+i
    line.set_data(x, y)
    ax.set_xlim(np.min(x), np.max(x))
    ax.set_ylim(np.min(y), np.max(y))
    plt.title(s)
    plt.draw()
    raw_input(s)

Only drawback is you have to keep the Window with the figure open. And without the raw_input the program will just run through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!