我有一个用 Python 构建的 Plotly 图形,可以自动更新。即使自动更新,我也想保留仪表板缩放。Plotly 中的文档表示,uirevision根据此社区文章,可以使用布局字段来完成此操作。文档给出了返回字典的示例:
return {
'data': data,
'layout': {
# `uirevsion` is where the magic happens
# this key is tracked internally by `dcc.Graph`,
# when it changes from one update to the next,
# it resets all of the user-driven interactions
# (like zooming, panning, clicking on legend items).
# if it remains the same, then that user-driven UI state
# doesn't change.
# it can be equal to anything, the important thing is
# to make sure that it changes when you want to reset the user
# state.
#
# in this example, we *only* want to reset the user UI state
# when the user has changed their dataset. That is:
# - if they toggle on or off reference, don't reset the UI state
# - if they change the color, then don't reset the UI state
# so, `uirevsion` needs to change when the `dataset` changes:
# this is easy to program, we'll just set `uirevision` to be the
# `dataset` value itself.
#
# if we wanted the `uirevision` to change when we add the "reference"
# line, then we could set this to be `'{}{}'.format(dataset, reference)`
'uirevision': dataset,
'legend': {'x': 0, 'y': 1}
}
}
Run Code Online (Sandbox Code Playgroud)
然而,我的身材更像是这样的:
import plotly.express as px
@app.callback(
Output("graph", "figure"),
[Input("interval-component", "n_intervals")])
def display_graph(n_intervals):
# Logic for obtaining data/processing is not shown
my_figure = px.line(my_data_frame, x=my_data_frame.index, y=['line_1', 'line_2'],
title='Some Title', template='plotly_dark')
return my_figure
Run Code Online (Sandbox Code Playgroud)
换句话说,由于我不是返回字典,而是直接返回一个绘图表达的图形,那么如何直接访问 uirevision 值以便保留用户的 UI 更改?
小智 5
您可以使用update_layout图中的成员函数。
my_figure.update_layout(uirevision=<your data>)
Run Code Online (Sandbox Code Playgroud)
更多信息请参见:https://plotly.com/python/creating-and-updating-figures/#updating-figure-layouts
使用图形字典,可以像这样访问:
my_figure['layout']['uirevision'] = 'some_value'
Run Code Online (Sandbox Code Playgroud)
这也可用于访问图形的其他有用方面,例如更改特定行条目的线条颜色:
my_figure['layout']['uirevision'] = 'some_value'
Run Code Online (Sandbox Code Playgroud)
要查看其他条目选项,请my_figure在 Python 会话中打印出来。
注意:由于该uirevision选项没有很好地记录(至少在我的在线搜索中没有),因此我认为值得将其作为选项发布。
| 归档时间: |
|
| 查看次数: |
3199 次 |
| 最近记录: |