我正在尝试使用Python(3.x)中的情节Dash(0.18.3)进行实时更新,但我不需要经常更新情节(每天一次或两次是我需要的)。
到目前为止我做了以下事情:
import dash
import pandas as pd
import plotly.graph_objs as go
import dash.dependencies as ddp
import dash_core_components as dcc
import dash_html_components as html
def plot_figure(data):
layout = dict(
title="Figure w/ plotly",
)
fig = dict(data=data, layout=layout)
return fig
def serve_layout():
return html.Div(children=[
html.Div([
html.H1("Plotly test with Live update",
style={"font-family": "Helvetica",
"border-bottom": "1px #000000 solid"}),
], className='banner'),
html.Div([dcc.Graph(id='plot')],),
dcc.Interval(id='live-update', interval=interval),
],)
second = 1000
minute = 60
hour = 60
day = 24
interval = 1/2*day*hour*minute*second
app = dash.Dash()
app.layout = serve_layout
@app.callback(
ddp.Output('plot', 'figure'),
[],
[],
[ddp.Event('live-update', 'interval')])
def gen_plot():
ind = ['a', 'b', 'c', 'd']
df = pd.DataFrame({'one' : pd.Series([4., 3., 2., 1.], index=ind),
'two' : pd.Series([1., 2., 3., 4.], index=ind)})
trace = [go.Scatter(x=df.index, y=df['one'])]
fig = plot_figure(trace)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
问题首先出现什么,它只在interval
之后更新,所以在半天之后。我在Dash documentation之后添加了serve_layout
函数,以便在加载页面时进行更新,但似乎没有效果。
如果首次访问该页面然后每interval
更新一次,我怎么能有第一次更新?
答案 0 :(得分:0)
根据对plotly forum的讨论,我找到了一个解决方案。您需要从gen_plot()
内部拨打serve_layout
以获取最新数据。要调用gen_plot
,您需要从中移除装饰器。
要在gen_plot
内拨打serve_layout
,我会在代码中向上移动,并在figure=gen_plot()
中将dcc.Graph
添加到serve_layout
。
import dash
import pandas as pd
import plotly.graph_objs as go
import dash.dependencies as ddp
import dash_core_components as dcc
import dash_html_components as html
second = 1000
minute = 60
hour = 60
day = 24
interval = 1/2*day*hour*minute*second
def plot_figure(data):
layout = dict(
title="Figure w/ plotly",
)
fig = dict(data=data, layout=layout)
return fig
def gen_plot():
ind = ['a', 'b', 'c', 'd']
df = pd.DataFrame({'one' : pd.Series([4., 3., 2., 1.], index=ind),
'two' : pd.Series([1., 2., 3., 4.], index=ind)})
trace = [go.Scatter(x=df.index, y=df['one'])]
fig = plot_figure(trace)
return fig
def serve_layout():
return html.Div(children=[
html.Div([
html.H1("Plotly test with Live update",
style={"font-family": "Helvetica",
"border-bottom": "1px #000000 solid"}),
], className='banner'),
html.Div([dcc.Graph(id='plot', figure=gen_plot())],),
dcc.Interval(id='live-update', interval=interval),
],)
app = dash.Dash()
app.layout = serve_layout
app.callback(
ddp.Output('plot', 'figure'),
[],
[],
[ddp.Event('live-update', 'interval')])(gen_plot)
if __name__ == '__main__':
app.run_server(debug=True)
请注意,在我的实际应用程序中,我还需要使用图片更新的文本摘录。我的gen_text
函数与我的gen_plot
函数具有相同的装饰器,我应用了相同的策略,并在相关的children=gen_text()
中添加了html.Div
个参数。就像一个魅力!