为什么在更新绘图时Jupyter Notebook会创建重复的绘图 [英] Why is Jupyter Notebook creating duplicate plots when making updating plots

查看:308
本文介绍了为什么在更新绘图时Jupyter Notebook会创建重复的绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Jupyter Notebook中进行绘制,并每秒钟更新一次.现在,我只有一个简单的代码可以正常工作:

I'm trying to make plots in a Jupyter Notebook that update every second or so. Right now, I just have a simple code which is working:

%matplotlib inline
import time
import pylab as plt
import numpy as np
from IPython import display

for i in range(10):
    plt.close()
    a = np.random.randint(100,size=100)
    b = np.random.randint(100,size=100)

    fig, ax = plt.subplots(2,1)
    ax[0].plot(a)
    ax[0].set_title('A')
    ax[1].plot(b)
    ax[1].set_title('B')

    display.clear_output(wait=True)
    display.display(plt.gcf())
    time.sleep(1.0)

每秒钟更新一次我创建的图.但是,最后还有一些情节的副本:

Which updated the plots I have created every second. However, at the end, there is an extra copy of the plots:

为什么要这样做?我该如何避免这种情况发生?预先谢谢你.

Why is it doing this? And how can I make this not happen? Thank you in advance.

推荐答案

已设置inline后端,以便在每个单元执行完后,将显示在该单元中创建的任何matplotlib图.

The inline backend is set-up so that when each cell is finished executing, any matplotlib plot created in the cell will be displayed.

使用display功能一次显示图形,然后内联后端自动再次显示图形.

You are displaying your figure once using the display function, and then the figure is being displayed again automatically by the inline backend.

防止这种情况的最简单方法是在单元格中的代码末尾添加plt.close().

The easiest way to prevent this is to add plt.close() at the end of the code in your cell.

这篇关于为什么在更新绘图时Jupyter Notebook会创建重复的绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆