如何彻底清除所有 Matplotlib 图的内存?

matplotlibserver side programmingprogramming更新于 2025/4/30 6:22:17

使用以下方法,我们可以清除 Matplotlib 图占用的内存。

  • plt.figure() - 创建新图形或激活现有图形。

  • plt.figure().close() -  关闭图形窗口。

    • close()  单独关闭当前图形

    • close(h),其中 h 是 Figure 实例,关闭该图形

    • close(num) 关闭图形编号 num

    • close(name),其中 name 是字符串,关闭带有该标签的图形

    • close('all') 关闭所有图形窗口

  • plt.figure().clear() - 与 clf 相同。

  • plt.cla() - 清除当前轴。

  • plt.clf() - 清除当前图形。

示例

from matplotlib import pyplot as plt
fig = plt.figure()
plt.figure().clear()
plt.close()
plt.cla()
plt.clf()

输出

当我们执行代码时,它将清除内存中的所有图。


相关文章