首页 > 解决方案 > Plotly Dash dcc.Interval 在一段时间后失败:回调错误更新 graph.figure

问题描述

我正在尝试将我的 Dash 应用程序设置为自动从数据框中使用的 .csv 文件中提取最新数据dcc.Interval。错误代码没有提供详细的解释,也并不总是出现。我已经尝试过使用按钮和设置的 6 秒间隔,但结果似乎是一样的。Dash 应用程序一开始运行良好,然后刷新几次,然后开始出现错误:

回调错误更新graph.figure

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd

app = dash.Dash(__name__)
server = app.server

df = pd.read_csv('example.csv', encoding="WINDOWS-1252")

app.layout = html.Div([
    dcc.Graph(id='graph'),
    dcc.Interval(
        id='interval-component',
        interval=1*6000,
        n_intervals=0
    )
])

@app.callback(
    Output('graph','figure'),
    [Input('interval-component', 'n_intervals')]
)

def update_df(n):
    updated_df = pd.read_csv('example.csv', encoding="WINDOWS-1252")
    
    fig = px.scatter(updated_df, x='Date', y='Deviation', height=800)
    
    fig.update_layout(
        yaxis_tickformat = '.0%', 
    )

    fig.update_xaxes(
        rangeslider_visible=True,
        rangeselector=dict(
        )
    )
    
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

标签: pythonpandasplotlyplotly-dash

解决方案


我认为您的问题一定与您的文件有关,因为以下代码完全基于您提供的内容(生成随机匹配 df 时间序列数据除外),可以以每 6 秒的间隔完美更新:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np

np.random.seed(2019)


def get_random_deviation_ts_df(N=100):
    rng = pd.date_range("2019-01-01", freq="D", periods=N)
    df = pd.DataFrame(np.random.rand(N, 1), columns=["Deviation"], index=rng)
    df["Date"] = df.index
    return df


app = dash.Dash(__name__)
server = app.server

# df = pd.read_csv('example.csv', encoding="WINDOWS-1252")

app.layout = html.Div(
    [
        dcc.Graph(id="graph"),
        dcc.Interval(
            id="interval-component", interval=1 * 6000, n_intervals=0
        ),
    ]
)


@app.callback(
    Output("graph", "figure"), [Input("interval-component", "n_intervals")]
)
def update_df(n):
    updated_df = (
        get_random_deviation_ts_df()
    )  # pd.read_csv('example.csv', encoding="WINDOWS-1252")

    fig = px.scatter(updated_df, x="Date", y="Deviation", height=800)

    fig.update_layout(yaxis_tickformat=".0%",)

    fig.update_xaxes(rangeslider_visible=True, rangeselector=dict())

    return fig


if __name__ == "__main__":
    app.run_server(debug=True)

间隔时间序列随机数据


推荐阅读