繁体   English   中英

如何关闭 matplotlib 中的图形?

[英]How do I close figure in matplotlib?

`

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 按钮,图形 window 也不会关闭。 我认为这是由于 while True。 我不知道如何解决这个问题,保持真。 请帮我!

  • 修改:当“第 2 个 window 尚未打开”输入消息出来时,我可以看到一个打开的 window。 可能,window 将是第一次循环的那个,因为当时没有打开第二个 window。 为什么第一个 window 还在? 我使用 plt.close() 关闭 window。

问题不在于while True:就像你如何创造你的人物一样。 让我们从概念上逐步完成您的过程:

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

要关闭正确的图形,请打开func内的图形。 使用面向 object 的 API 可以让您更好地控制打开、关闭、plot 等的内容:

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()) ,因此您不必知道新图形的句柄。

每次执行新循环时,都会创建一个新的 window。 您可以关闭此 window,但会立即重新出现一个新的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM