基本上,我有一个使用滑块和暂停/播放按钮浏览数据集的 Plotly 动画。我想在 Dash 回调中提取当前帧的编号(即滑块所处的“步骤”/“帧”列表中的当前索引),以便我可以根据主图更新表格。
例如,在这种情况下: Dash app with slider 我想从图表中获取“6”,即当前步骤编号。
以下是一些示例代码,其中包含一个玩具数据集,但具有相同的基本 UI 和结构(来自上面的代码块,减去减少代码块长度的按钮):
基本上,在那个回调函数中,我只想获取滑块的当前索引,即动画所在的当前帧。它由滑块上方的“步骤”标签显示,因此它显然存在于某个地方,但我无论如何都找不到它(尝试查看Github源代码,但找不到它)。
我真的很感激任何帮助!我的数据集相当大(20 MB),无法适应浏览器内存,因此我在使用dcc.Slider和dcc.Graph的Dash解决方案方面并没有取得太大的成功。
例如,在这种情况下: Dash app with slider 我想从图表中获取“6”,即当前步骤编号。
以下是一些示例代码,其中包含一个玩具数据集,但具有相同的基本 UI 和结构(来自上面的代码块,减去减少代码块长度的按钮):
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# Dataset
x = [10, 1, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 1, 3, 4, 5, 6, 7, 8, 9, 10]
df = pd.DataFrame(list(zip(x, y)), columns = ['x', 'y'])
# Adding a trace
trace = go.Scatter(x=df.x[0:2], y=df.y[0:2],
name='Location',
mode='markers',
marker=dict(color="white",
size=10,
line=dict(
color='DarkSlateGrey',
width=2)
)
)
# Adding frames
frames = [dict(name=k,data= [dict(type='scatter',
x=df.x[k:k + 1],
y=df.y[k:k + 1],
),
],
traces = [0],
) for k in range(len(df) - 1)]
fig = go.Figure(data=[trace], frames=frames)
# Adding a slider
sliders = [{
'yanchor': 'top',
'xanchor': 'left',
'active': 1,
'currentvalue': {'font': {'size': 16}, 'prefix': 'Steps: ', 'visible': True, 'xanchor': 'right'},
'transition': {'duration': 200, 'easing': 'linear'},
'pad': {'b': 10, 't': 50},
'len': 0.9, 'x': 0.15, 'y': 0,
'steps': [{'args': [[k], {'frame': {'duration': 200, 'easing': 'linear', 'redraw': False},
'transition': {'duration': 0, 'easing': 'linear'}}],
'label': k, 'method': 'animate'} for k in range(len(df) - 1)
]}]
fig['layout'].update(sliders=sliders)
app.layout = html.Div(children=[
html.Div([
dcc.Graph(
id= 'my-graph',
figure=fig
),
html.Br(),
html.Div(id='my-output'),
])
])
@app.callback(
Output(component_id='my-output', component_property='children'),
Input(component_id='my-graph', component_property='figure')
)
# How to get the current frame index here?
def update_output_div(figure):
return 'Output: {}'.format(figure['layout']['sliders'][0])
if __name__ == '__main__':
app.run_server(debug=True)
基本上,在那个回调函数中,我只想获取滑块的当前索引,即动画所在的当前帧。它由滑块上方的“步骤”标签显示,因此它显然存在于某个地方,但我无论如何都找不到它(尝试查看Github源代码,但找不到它)。
我真的很感激任何帮助!我的数据集相当大(20 MB),无法适应浏览器内存,因此我在使用dcc.Slider和dcc.Graph的Dash解决方案方面并没有取得太大的成功。