【问题标题】:Show only the last plot in Python using MatPlotLib使用 MatPlotLib 仅显示 Python 中的最后一个图
【发布时间】:2020-10-20 11:02:30
【问题描述】:

我正在使用带有 MatPlotLib 包的 Python 3.5。我的问题如下: 我生成了 50 个图,每个图都保存到 PNG 文件中。然后我生成 2 个汇总图,我希望将其保存并在显示器上显示。但是,当我使用plt.show() 命令时,它还显示了之前的所有 50 个图,我不想显示,只需保存它们即可。如何抑制前 50 个图上的显示,只显示最后一个?

这是一个示例代码:

import matplotlib.pyplot as plt
import numpy as np

for i in range(50):
   fig = plt.figure()
   plt.plot(np.arange(10),np.arange(10)) # just plot something
   plt.savefig(f"plot_{i}.png")
   # I want to save these plots but not show them
# summarizing plot
fig = plt.figure()
plt.plot(np.arange(100),np.arange(100))
plt.show() # now it shows this fig and the previous 50 figs, but I want only to show this one!

【问题讨论】:

  • 你需要plt.clf()在绘制最终数字之前清除之前的数字
  • plt.clf() 只清除最后一个(当前)图形,这样当您plt.show() 时,您将获得 49 个带有绘图的图形,最后一个已清除并汇总图形。

标签: python python-3.x matplotlib


【解决方案1】:

循环结束后全部关闭:

plt.close("all") #this is the line to be added
fig = plt.figure()
plt.plot(np.arange(100),np.arange(100))
plt.show()

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2022-09-15
    • 2018-09-03
    • 2018-06-21
    • 1970-01-01
    相关资源
    最近更新 更多