python - 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)
解决方案
我认为您的问题一定与您的文件有关,因为以下代码完全基于您提供的内容(生成随机匹配 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)
推荐阅读
- reactjs - Formik 表格不会清除
- swift - Swift 值类型语义和绑定的影响
- pandas - 大熊猫中的数据透视表以计算唯一值
- css - 如何减少布尔玛的班级列表
- html - Bootstrap 表单列对齐
- python - 通过计算更改列值
- sql - 从 SQL 列中删除重复项
- antlr - Antlr4:输入不匹配
- javascript - 如何使用 axios、multer 将 React Native Image Customized Picker 中的多张图片上传到 Node Server?
- laravel - 验证电子邮件后,Laravel Breeze 正在转发到登录页面