【问题标题】:Confusion about plotly offline and updating a graph in jupyter notebook关于离线绘图和更新 jupyter notebook 中的图表的困惑
【发布时间】:2018-07-09 12:01:09
【问题描述】:

我的问题与此SO post 有关。但是,我不想使用交互,而是想用按钮调用 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)

【问题讨论】:

    标签: python jupyter-notebook plotly ipywidgets


    【解决方案1】:

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

    当您单击按钮时,您可以改为使用笔记本自己的 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()
    

    【讨论】:

      猜你喜欢
      • 2018-10-28
      • 2018-01-27
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多