【问题标题】:Why does python keep crashing when plotting with matplotlib?为什么 python 在使用 matplotlib 绘图时会不断崩溃?
【发布时间】:2015-07-22 13:50:26
【问题描述】:

我正在运行一个 python 代码来模拟和预测快速压缩机器内部的条件(例如温度、压力、化学物质等)。设置代码以便计算所有这些参数的时间演变(保存在 numpy 数组中),然后将它们输出到一个函数,该函数创建并保存这些参数与时间的关系图。

这些数组非常大,该函数使用 matplotlib 创建了大约 14 个图。当我收到错误消息“python.exe 已停止工作”时,该函数将到达大约第 7 个图(有时更多,有时更少)。不确定这是否是内存问题,因为情节太大或发生了什么。

plt.figure.clf()plt.close() 我都试过了(正如您将在我的示例代码中看到的那样)。我什至尝试在地块之间做一个time.sleep。以下是我的函数的示例 sn-p 进行绘图(不是真正的代码,只是说明我的问题所必需的示例)。

我使用的是 Windows、Python 2.7 和 Matplotlib 1.4.2

def graph_parameters(time, a, b, c, d, e):  #a,b,c,d,e are my parameters

    delay = 10

    plt.figure(1)
    plt.figure(facecolor="white")
    plt.plot(time, a)
    plt.ylabel('a')
    plt.xlabel('Time(s)')
    plt.savefig('fig1.png')
    plt.figure(1).clf()
    plt.close('all')
    time.sleep(delay)

    plt.figure(2)
    plt.figure(facecolor="white")
    plt.plot(time, b)
    plt.ylabel('b')
    plt.xlabel('Time(s)')
    plt.savefig('fig2.png')
    plt.figure(2).clf()
    plt.close('all')
    time.sleep(delay) 

等等

提前致谢。

【问题讨论】:

  • 你检查过你的内存消耗吗?
  • 不,我没有。我对编程比较陌生。我该怎么做?
  • 您能否尝试更新您的示例以生成示例数据,以便重现您所看到的行为?您发布的代码看起来很无辜......

标签: python numpy matplotlib plot


【解决方案1】:

我不完全确定,但我认为这是内存问题。我找到了一种方法(从另一个 stackoverflow 条目)删除我不需要的变量。根据我上面的示例,如果我只想保留 'time_' 和参数 'a_'、'b_'、'c_'、'd_' 和 'e_',我会在主代码的末尾运行以下命令:

graph_array = np.array([time_, a_, b_, c_, d_, e_])

#Delete variables that aren't going to be plotted in order to free up memory
attributes = sys.modules[__name__]

for name in dir():
   if name[0]!='_' and np.all( name!= np.array(['graph_array', 'attributes','np', 'gc', 'graph_parameters']) ):
     delattr(attributes, name)

gc.collect()

graph_parameters(*graph_array)

for 循环所做的基本上是保留私有和神奇的函数名称和指定变量的名称,并删除所有其他名称。我从以下链接的答案中得到了这个想法。 How do I clear all variables in the middle of a Python script?

我在代码运行时观察了我的任务管理器,在开始保存绘图之前,Python 的内存使用量显着下降(~1,600,000 K 到 ~100,000 K),这表明这种方法确实释放了内存。此外,没有崩溃。

【讨论】:

    猜你喜欢
    • 2013-10-23
    • 1970-01-01
    • 2016-12-18
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2011-04-17
    相关资源
    最近更新 更多