[英]Freeze plotly-dash graph visualization
我正在开发一个破折号应用程序,这是我的代码:
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
blue = '#6683f3'
orange = '#ff9266'
grey = '#e0e1f5'
black = '#212121'
app = dash.Dash()
app.layout = html.Div([html.Div([dcc.RadioItems(id = 'radio-item',
options = [dict(label = 'squared',
value = '2'),
dict(label = 'cubed',
value = '3')],
value = '2',
labelStyle = {'display': 'block'})]),
html.Div(dcc.Graph(id = 'graph',
figure = dict(data = [],
layout = go.Layout(plot_bgcolor = black)),
style = dict(height = 1000)))])
@app.callback(Output('graph', 'figure'),
[Input('radio-item', 'value')])
def update_graph(value):
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
XX, YY = np.meshgrid(x, y)
Z1 = XX ** int(value) * YY
Z2 = XX ** int(value) / YY
data = [go.Contour(z = Z1,
name = f'Z1',
zmin = 0,
zmax = 100,
contours_coloring = 'lines',
line_width = 2,
showscale = False,
showlegend = True,
visible = True,
colorscale = [[0, orange], [1, orange]],
ncontours = 21,
contours = dict(showlabels = True,
labelformat = '.0f')),
go.Contour(z = Z2,
name = f'Z2',
zmin = 0,
zmax = 100,
contours_coloring = 'lines',
line_width = 2,
showscale = False,
showlegend = True,
visible = True,
colorscale = [[0, blue], [1, blue]],
ncontours = 21,
contours = dict(showlabels = True,
labelformat = '.0f'))]
layout = go.Layout(plot_bgcolor = black,
hovermode = 'x unified')
figure = go.Figure(data = data, layout = layout)
figure.update_xaxes(title_text = 'X',
linewidth = 1,
nticks = 11,
gridwidth = 0.5,
gridcolor = grey,
tickformat = '.0f')
figure.update_yaxes(title_text = 'Y',
linewidth = 1,
nticks = 11,
gridwidth = 0.5,
gridcolor = grey,
tickformat = '.0f')
figure.update_layout(legend = dict(itemsizing = 'constant'))
return figure
if __name__ == "__main__":
app.run_server()
此代码生成一个图形和一个带有两个选项的RadioItems
。 图表的内容通过update_graph
function 相应地更新为RadioItems
selected 选项。 到目前为止,一切都很好。
当我缩放/平移图形然后更改 RadioItems 选项时出现问题:图形已正确更新,但它丢失了我之前所做的缩放/平移。 如果我显示/隐藏两条迹线之一,然后更改 RadioItems 选项,则会出现同样的问题:图表已更新,但迹线的可视化选项已重置。
这种行为是由于我的代码:当用户更改RadioItems
选项时,它被称为 function update_graph
重置图形,因此平移/缩放或隐藏/显示跟踪选项等属性丢失。
我想冻结这些可视化选项,以便当用户平移/缩放然后他更改RadioItems
选项时,图形会正确更新,但它会保留用户之前所做的平移/缩放。 跟踪隐藏/显示选项也是如此。
我认为有一种方法可以将当前显示区域保存在一个变量中,并将迹线的可见性保存在另一个变量中,并在update_graph
中调用这些变量,但我不知道如何保存和调用这些属性。
版本信息:
Python 3.7.0
dash 1.12.0
dash-core-components 1.10.0
dash-html-components 1.0.3
dash-renderer 1.4.1
plotly 4.8.1
我相信您正在寻找的是uirevision
属性(有关详细信息,请参阅文档)。 要保持缩放、平移等,请在更新图形时设置此属性,即
fig['layout']['uirevision'] = 'something'
您设置的值无关紧要(您可以使用数字、字符串等),重要的是该值在后续更新期间保持不变(您不想保持缩放、平移等)。 )。 每当您需要重置视图时,将值更改为其他值,例如
fig['layout']['uirevision'] = 42
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.