matplotlib.close()不关闭绘图

时间:2019-01-31 13:33:29

标签: python matplotlib jupyter-notebook

我在jupyter笔记本中使用Python 3.6。 plt.close不会关闭情节。我也尝试了plt.ion()和其他许多方式。

我要显示图像,然后等待暂停或input(),然后删除上一张图像并显示新的图像。

csv <- "a,b\n1,a\n2,c\n" # input

# 1
library(readr)
read_csv(csv, col_types = "nc")

# 2
read.csv(text = csv, colClasses = c("numeric", "character"))

# 3
library(data.table)
fread(csv, colClasses = c("numeric", "character"))

2 个答案:

答案 0 :(得分:1)

这是一个显示一系列图的示例,每个图持续一秒钟。必要的是plt.show(block = False)plt.pause(1)而不是sleep(1)

import numpy as np
import matplotlib.pyplot as plt

def show_image(n):
    fig, ax = plt.subplots()
    x = np.linspace(0,1,100)
    y = x**n
    ax.plot(x,y, label = 'x**{}'.format(n))
    ax.legend()
    plt.show(block=False)
    plt.pause(1)
    plt.close(fig)



for i in range(10):
    show_image(i)

答案 1 :(得分:0)

如果我正确理解,您想要显示的是绘图,请等待1秒钟,然后自动关闭。

这将通过以下方式实现。

import matplotlib.pyplot as plt
from scipy import eye

plt.imshow(eye(3))

def show_and_close(sec):
    timer = plt.gcf().canvas.new_timer(interval=sec*1000)
    timer.add_callback(lambda : plt.close())
    timer.single_shot = True
    timer.start()
    plt.show()

show_and_close(1)