如何在 matplotlib 中关闭图形?

问题描述 投票:0回答:1
import matplotlib.pyplot as plt
import pandas as pd
l1 = [1,2,3,4]
l2 = [2,4,6,8]
fig = plt.figure()


def func():
    plt.pause(1)
    plt.plot(l1,l2)
    plt.draw()
    plt.pause(1)
    input("press any key to continue...")
    plt.close(fig)
    plt.pause(1)

while True:
    func()
    plt.pause(1)

这是修改后的:

import matplotlib.pyplot as plt
import pandas as pd
l1 = [1,2,3,4]
l2 = [2,4,6,8]
fig = plt.figure()
a = 1

def func(num):
    input(f"the {num}th window is not opened yet")
    plt.pause(1)
    plt.plot(l1,l2)
    plt.draw()
    print(f"the {num}th window is opened")
    plt.pause(1)
    input("press any key to continue...")
    plt.close(fig)
    plt.pause(1)
    print(f"the {num}th window is closed")
while True:
    func(a)
    plt.pause(1)
    a+=1

如果我不使用 while True 循环,当我按任意键时它就会停止运行,这就是我的意图。但是,如果我使用 while True 循环运行此代码,即使我按左上角的任意键或 x 按钮,图形窗口也不会关闭。我认为这是由于 while True 。我不知道如何解决这个问题,保持 True 。请帮助我!

  • 修改: 当“第二个窗口尚未打开”输入消息出现时,我可以看到一个打开的窗口。该窗口可能是第一次循环时的窗口,因为当时尚未打开第二个窗口。为什么第一个窗口还在那里?我使用 plt.close() 关闭窗口。
python matplotlib
1个回答
7
投票

问题不在于

while True:
,而在于如何创建图形。让我们从概念上逐步了解您的流程:

  1. fig = plt.figure()
    创建一个图形并将句柄存储在
    fig
    中。
  2. 然后您调用
    func
    ,它会在图形上绘制并最终调用
    plt.pause(1)
  3. 你绕了一圈,再次呼叫
    func
    。这次,
    plt.plot(l1, l2)
    创建了一个new图形,因为没有开放的图形。
  4. func
    致电
    plt.close(fig)
    。但是存储在
    fig
    中的句柄不是您打开的 new 图形,所以您的图形当然不会关闭。

要关闭正确的图形,请打开

func
内的图形。使用面向对象的 API 可以让您更好地控制打开、关闭、绘图等内容:

import matplotlib.pyplot as plt
import pandas as pd

l1 = [1, 2, 3, 4]
l2 = [2, 4, 6, 8]

def func():
    fig, ax = plt.subplots()
    ax.plot(l1, l2)
    plt.show(block=False)
    plt.pause(1)
    input("press any key to continue...")
    plt.close(fig)
    plt.pause(1)

while True:
    func()

或者,您可以将

plt.close(fig)
替换为
plt.close()
,这相当于
plt.close(plt.gcf())
,这样您就不必知道新图形的句柄。

© www.soinside.com 2019 - 2024. All rights reserved.