在 jupyter 中更新 plotly 图 [每隔几秒]

updating plotly figure [every several seconds] in jupyter

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

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

...
  • 鉴于您希望在数据到达时进行更新,您需要一种事件/中断处理方法
  • 这个例子使用时间作为事件/中断,一个dash Interval
  • 通过将附加数据连接到数据帧来模拟更多数据,然后更新 回调
  • 中的
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")