[英]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。 我不知道如何解决这个问题,保持真。 请帮我!
问题不在于while True:
就像你如何创造你的人物一样。 让我们从概念上逐步完成您的过程:
fig = plt.figure()
创建一个图形并将句柄存储在fig
中。func
,它在图上绘制并最终调用plt.pause(1)
。func
。 这一次, plt.plot(l1, l2)
创建了一个新图形,因为没有打开的图形。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.