How to clear memory completely of all Matplotlib plots

后端 未结 3 602
粉色の甜心
粉色の甜心 2020-12-05 17:50

I have data analysis module that contains functions which call on Matplotlib pyplot API multiple times to generate up to 30 figures in each run. These figures get immediatel

3条回答
  •  被撕碎了的回忆
    2020-12-05 18:26

    Late answer, but this worked for me. I had a long sequential code generating many plots, and it would always end up eating all the RAM by the end of the process. Rather than calling fig.close() after each figure is complete, I have simply redefined the plt.figure function as follows, so that it is done automatically:

    import matplotlib.pyplot as plt
    import copy
    try:
       # if script it run multiple times, only redefine once
       plt.old_figure
    except:
      # matplotlib is imported for the first time --> redefine
      plt.old_figure = copy.deepcopy(plt.figure)
      def newfig(*args):
        plt.show()
        plt.close("all")
      return plt.old_figure(*args)
      plt.figure = newfig
    

    I am well aware that this is not a nice solution, however it easy, quick, and did the trick for me ! Maybe there's a way to decorate plt.figure instead of redefining it.

提交回复
热议问题