【问题标题】:Closing Matplotlib figures [duplicate]关闭 Matplotlib 数字 [重复]
【发布时间】:2014-08-21 09:52:19
【问题描述】:

我正在使用 Matplotlib 和 MPLD3 创建可以在 html plages 中显示的图形(使用 django)。目前,我的图表是根据从 csv 文件中提取的数据动态生成的。每隔一段时间,我就会在终端中收到此消息:

运行时警告:已打开 20 多个图形。通过 pyplot 接口 (matplotlib.pyplot.figure) 创建的图形会一直保留到明确关闭,并且可能会消耗太多内存。 (要控制此警告,请参阅 rcParam figure.max_num_figures)。 max_open_warning, RuntimeWarning)

我不太确定这意味着什么,但我假设这意味着我应该有一些方法来关闭未使用的图表。无论如何要这样做还是我完全不在基地?谢谢。

【问题讨论】:

  • 不确定这是最好的副本。简短的回答是你应该在完成后清理你的地块:plt.close(fig)plt.close('all')
  • @tcaswell 为什么不添加这个作为答案?

标签: python matplotlib


【解决方案1】:

我更喜欢 cmets 中tacaswell 的答案,但不得不搜索它。

完成后清理你的地块:

plt.close(fig)

plt.close('all')

【讨论】:

  • 奇怪,那为什么没有图中的close()方法呢。
  • 是的!为什么fig.close() 不起作用?
  • @DanHickstein 关闭方法似乎没有在图上实现(参考matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html
  • 我正在使用 matpltlib 版本:3.0.3 并且 plt.close() 对我有用。
【解决方案2】:

如果您不通过 pyplot 界面创建图形,它们将自动关闭(通过垃圾收集)。例如,您可以使用以下方法创建图形:

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure


def new_fig():
    """Create a new matplotlib figure containing one axis"""
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)

    return fig, ax

(基于this answer

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多