You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除循环中未触发plt.show()的subplot对象以避免空白绘图窗口

解决方案

你只需在should_plot为False的分支中调用plt.close(fig)关闭当轮创建的未使用画布即可,修改后的代码如下:

while True:
    # Get a key from keyboard and if it is 'q' exit the loop, otherwise do the following
    fig,axes = plt.subplots(2,1, figsize=(20, 15))
    should_plot = plot_dataframe(df, axes)
    if should_plot == True:
        for ax in axes:
            ax.legend()
        plt.show()
    else:
        # 关闭当前未使用的画布,避免残留空白窗口
        plt.close(fig)

原理解释

  • 每次调用plt.subplots()都会生成一个全新的Figure画布对象,即使不执行plt.show(),该对象也会保存在matplotlib的待渲染队列中,等到下一次调用plt.show()时,所有未关闭的画布会被同时渲染弹出,就是你看到多个空白窗口的原因。
  • 直接将当轮生成的fig对象传入plt.close(),可以精准销毁不需要的画布,不会影响其他正常绘图流程,也不会产生内存残留。

内容的提问来源于stack exchange,提问作者mahmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:15:04