关于 jupyter notebook 中 plotly offline 和更新图表的困惑

Confusion about plotly offline and updating a graph in jupyter notebook

我的问题与此有关。但是,我不想使用交互,而是想用一个按钮调用 iplot。不幸的是,该图在同一个单元格中多次显示。有什么办法可以避免吗?

#%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np

import ipywidgets as widgets

import plotly.plotly as ply
import plotly.graph_objs as go
from plotly.widgets import GraphWidget
from plotly.offline import init_notebook_mode, iplot, plot

init_notebook_mode(connected=True)

#%%
def plotly_kin(x, y, color_list):
    """ A generic plot function for x,y line plots
    """
    # pop the first item from the colormap
    try:
        color = color_list.pop(0)
    except AttributeError:
        # reameke the colormap
        color_list = list(plt.cm.tab10.colors)
        color = color_list.pop(0)

    # create a line object
    line = go.Scatter(x=x, y=y, mode='scatter', name='test')
    # make a data object
    traces.append(line)
    iplot(traces, show_link=False)

#%%
traces = []

#%% this part works just fine
x = np.arange(0,10)
y = np.random.normal(size=len(x))

plotly_kin(x, y, 'a')

输出总是在同一个图中:

但是,这部分不起作用,因为数字附加到单元格输出:

def test_plot(message):
    x = np.arange(0,10)
    y = np.random.normal(size=len(x))
    plotly_kin(x, y, 'a')

button_test = widgets.Button(description='test')
button_test.on_click(test_plot)
display(button_test)

问题是点击按钮并没有清除单元格之前的输出。如果您使用的是 matplotlib,这可以通过先创建图形和轴并仅在单击按钮时更新数据来解决,但我认为 plot.ly.[=13= 不可能做到这一点]

您可以改为使用笔记本自己的 API 在单击按钮时删除现有的单元格输出。这也会删除按钮,因此在按钮代码的末尾您需要重新创建按钮。

from IPython.display import clear_output

def test_plot(message):
    clear_output()
    x = np.arange(0,10)
    y = np.random.normal(size=len(x))
    plotly_kin(x, y, 'a')
    create_button()

def create_button():
    button_test = widgets.Button(description='test')
    button_test.on_click(test_plot)
    display(button_test)

create_button()