【发布时间】:2021-04-27 11:42:20
【问题描述】:
我正在开发一种工具,通过 Dash 滑块修改这些参数来可视化一组参数对数学函数的影响。我正在使用一些 Dash 教程示例中的方法,这些示例使用回调来替换图形。
这可行,但绘图对滑块变化的响应不如内置操作(例如通过拖动旋转绘图)。当图中的元素很多时尤其如此。
是否有不同的方法可以提高响应能力?例如,有没有办法只针对发生变化的绘图元素而不是替换整个图形?
这是一个最小的工作示例,由一个静态圆(有许多样本)和一个我们通过滑块旋转的线段组成。线段的旋转很不稳定。
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
from dash.dependencies import Input, Output, State
import numpy as np
app = dash.Dash(__name__)
# plot a circle
t = np.linspace(0, 2*np.pi, 10000) # intentionally use many points to exaggerate the issue
x = np.cos(t)
y = np.sin(t)
z = np.zeros_like(t)
marker_size = 4
fig = go.Figure()
fig.add_trace(go.Scatter3d(x=x, y=y, z=z, mode='lines'))
fig.add_trace(go.Scatter3d(
x=[0.0, 0.0], y=[0.0, 0.0], z=[0.0, 0.0],
marker=go.scatter3d.Marker(size=marker_size),
line=dict(width=3.0),
showlegend=False,
))
fig.update_layout(
uirevision='constant',
autosize=False,
width=900,
height=900,
scene=dict(
xaxis=dict(range=[-1, 1]),
yaxis=dict(range=[-1, 1]),
zaxis=dict(range=[-1, 1.0]),
aspectratio=dict(x=2, y=2, z=2),
),
)
app.layout = html.Div(children=[
dcc.Graph(
id='example-graph',
figure=fig
),
html.Div(
[
dcc.Slider(
id='slider-phi',
min=0.0,
max=360.0,
step=1.0,
value=0.0,
marks={0: '0', 180: '180', 360: '360'},
updatemode='drag',
),
],
style=dict(width='50%'),
),
html.Div(children='', id='output-box'),
])
@app.callback(
Output('example-graph', 'figure'),
[Input('slider-phi', 'value')],
[State('example-graph', 'figure')]
)
def display_structure(phi, myfig):
myfig['data'][1]['x'][1] = np.cos(np.radians(phi))
myfig['data'][1]['y'][1] = np.sin(np.radians(phi))
myfig['data'][1]['z'][1] = 0
return myfig
if __name__ == '__main__':
app.run_server(debug=True)
【问题讨论】:
-
我认为出现这种情况的原因是由于实时绘制需要大量的计算。我通过将图形的大小减半并使用步长值 10 来检查操作。拖动滑块也会随之而来。
标签: python plotly plotly-dash