天天看點

X Error of failed request: BadAlloc (insufficient resources for operation)

報錯資訊

X Error of failed request: BadAlloc (insufficient resources for operation)

原因分析

報錯代碼中多次使用matplot.pyplot畫圖。但是由于matplotlib維護的Figure是有數量上限的(RuntimeWarning: More than 20 figures have been opened.),不斷建立新的Figure執行個體,不及時處理的話很容易造成記憶體洩漏。

解決思路

是以需要對Figure執行個體進行

及時清理

或者

合理複用

,下面需要用到的代碼:

plt.cla() # 清除axes,即目前 figure 中的活動的axes,但其他axes保持不變。
plt.clf() # 清除目前 figure 的所有axes,但是不關閉這個 window,是以能繼續複用于其他的 plot。
plt.close() # 關閉 window,如果沒有指定,則指目前 window。
           

思路1:合理複用

隻建立一個 Figure 對象,在畫下一個圖之前,使用 plt.clf() 清理掉 axes,這樣可以複用 Figure執行個體。

示例:

import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
fig, axe = plt.subplots(2,2)
axe[0][0].plot([0,1],[0,1])
axe[1][1].plot([0,1],[1,0])
plt.show()
plt.savefig('test.png')
plt.clf()

fig2 = plt.gcf() #擷取目前的圖示(Figure執行個體)
print(f'fig is fig2 : {fig is fig2}')
# fig is fig2 : True

axe = fig2.subplots(2,3) #重新規劃為2*3個子圖
axe[0][0].plot([0,1],[0,1])
axe[1][1].plot([0,1],[1,0])
plt.show()
           
X Error of failed request: BadAlloc (insufficient resources for operation)
X Error of failed request: BadAlloc (insufficient resources for operation)

思路2: 及時清理

及時清除并且關閉掉 Figure 對象,但是要注意這樣頻繁的 “建立→清除” 是會拖慢你的代碼運作速度的。

plt.cla()
plt.close("all")
           

參考

  1. 【matplotlib】 之 清理、清除 axes 和 figure (plt.cla、plt.clf、plt.close)