【问题标题】:updating plotly figure [every several seconds] in jupyter在 jupyter 中 [每隔几秒] 更新 plotly 图形
【发布时间】:2021-10-14 06:29:06
【问题描述】:

我是 plotly python 包的新手,遇到过这样的问题:
有一个 pandas 数据框正在循环更新,我必须使用 plotly 从中绘制数据。
一开始所有df.response 值都是None,然后它开始填充它。这是一个例子:
at the beginning
after it starts to fill
我想巧妙地对这些变化做出反应,但我不知道如何以最“规范”和简单的方式来做到这一点。 (如果数据更新循环和情节更新能够同时工作,那就太好了,但如果情节每隔几秒钟就会做出反应,那也很好)。我发现了一些功能,但并不完全了解它们的工作原理:

import plotly.graph_objects as go
import cufflinks as cf
from plotly.offline import init_notebook_mode

init_notebook_mode(connected=True)
cf.go_offline()

fig = go.Figure(data=go.Heatmap(z=df.response,
                                x=df.currents,
                                y=df.frequencies))

fig.update_layout(datarevision=???) # This one

...

【问题讨论】:

    标签: python pandas jupyter-notebook plotly python-multiprocessing


    【解决方案1】:
    • 如果您想在数据到达时进行更新,您需要一种事件/中断处理方法
    • 此示例使用时间作为事件/中断,dash Interval
    • 通过将其他数据连接到数据帧来模拟更多数据,然后更新 回调 中的 figure
    import plotly.graph_objects as go
    import numpy as np
    import pandas as pd
    from jupyter_dash import JupyterDash
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output, State
    
    # initialise dataframe and figure
    df = pd.DataFrame({"response":[], "currents":[], "frequencies":[]})
    fig = go.Figure(data=go.Heatmap(z=df.response,
                                    x=df.currents,
                                    y=df.frequencies))
    
    
    
    # Build App
    app = JupyterDash(__name__)
    app.layout = html.Div(
        [
            dcc.Graph(id="heatmap", figure=fig),
            dcc.Interval(id="animateInterval", interval=400, n_intervals=0),
        ],
    )
    
    @app.callback(
        Output("heatmap", "figure"),
        Input("animateInterval", "n_intervals"),
        State("heatmap", "figure")
    )
    def doUpdate(i, fig):
        global df
        df = pd.concat([df, pd.DataFrame({"response":np.random.uniform(1,5,100), "currents":np.random.randint(1,20,100), "frequencies":np.random.randint(1,50,100)})])
    
        return go.Figure(fig).update_traces(go.Heatmap(z=df.response,
                                    x=df.currents,
                                    y=df.frequencies))
    
    
    # Run app and display result inline in the notebook
    app.run_server(mode="inline")
    

    【讨论】:

    • 谢谢!这对我帮助很大!
    猜你喜欢
    • 2010-12-17
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多