python - 如何更新绘图并保留 UI 设置?
问题描述
以下代码创建两个子图并在浏览器窗口中每秒更新一次。
我可以缩放它并隐藏绘图中的一些线条,但每秒所有数据都会更新并将缩放和所有线条可见性设置为默认值
如何在更新时保留缩放和选定线的设置?
import datetime
import random
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from plotly.subplots import make_subplots
# https://dash.plotly.com/live-updates
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
html.Div([
html.H4('Two random plots'),
dcc.Graph(id='live-update-graph'),
dcc.Interval(
id='interval-component',
interval=1 * 1000, # in milliseconds
n_intervals=0
)
])
)
DATA = {
'time': [],
'val0': [],
'val1_1': [],
'val1_2': []
}
def update_data():
DATA['val0'].append(random.randint(0, 50))
DATA['val1_1'].append(random.randint(0, 50))
DATA['val1_2'].append(random.randint(0, 50))
DATA['time'].append(datetime.datetime.now())
@app.callback(Output('live-update-graph', 'figure'),
Input('interval-component', 'n_intervals'))
def update_graph_live(n):
update_data()
# Create the graph with subplots
fig = make_subplots(rows=2, cols=1, vertical_spacing=0.2)
fig['layout']['margin'] = {'l': 30, 'r': 10, 'b': 30, 't': 10}
fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'}
fig.append_trace({
'x': DATA['time'],
'y': DATA['val0'],
'name': 'val 0',
'mode': 'lines+markers',
'type': 'scatter'
}, 1, 1)
fig.append_trace({
'x': DATA['time'],
'y': DATA['val1_1'],
'text': DATA['time'],
'name': 'val 1.1',
'mode': 'lines+markers',
'type': 'scatter'
}, 2, 1)
fig.append_trace({
'x': DATA['time'],
'y': DATA['val1_2'],
'text': DATA['time'],
'name': 'val 1.2',
'mode': 'lines+markers',
'type': 'scatter'
}, 2, 1)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
解决方案
自 2018 年 11 月以来,Plotly 社区论坛上发布了一个解决方案。的layout
财产的figure
财产dcc.Graph
有一个财产uirevision
,帖子说:
uirevision
是魔法发生的地方。此键由 内部跟踪dcc.Graph
,当它从一个更新更改为下一个更新时,它会重置所有用户驱动的交互(如缩放、平移、单击图例项)。如果它保持不变,那么用户驱动的 UI 状态就不会改变。
因此,如果您不想重置缩放设置,无论底层数据发生多少变化,只需设置uirevision
为常量,如下所示:
fig['layout']['uirevision'] = 'some-constant'
在更新函数中返回图形之前。
还有更多:
在某些情况下,您需要更多控制权。假设绘图的 x 和 y 数据可以单独更改。也许 x 总是时间,但 y 可以在价格和数量之间变化。您可能希望在重置 y 缩放时保留 x 缩放。有很多
uirevision
属性,通常都继承自,layout.uirevision
但如果需要,您可以单独设置它们。在这种情况下,设置一个常数xaxis.uirevision = 'time'
,但让和yaxis.revision
之间变化。确保仍然设置以保留其他项目,例如跟踪可见性和模式栏按钮!'price'
'volume'
layout.uirevision
推荐阅读
- c# - 如何处理第三方 API
- python - 检查数据框列的列表成员资格并附加结果?
- xslt - 如何使用带有 Xpath 替换功能的案例替换模式
- windows - 使用 PowerShell Direct 时通过 psexec 打开的窗口为空白,但在本地启动 psexec 时正常
- javascript - Firefox 增强的隐私保护正在阻止将数据层推送到谷歌标签管理器
- javascript - react-native - 如何在选择器中居中对齐文本
- css - Parcel PostCSS 预处理/动态导入不起作用
- javascript - 来自字符串的 JavaScript 日期。意想不到的结果
- python - 从 PEP518 环境 (pyproject.toml) 中的另一个包访问非 Python 文件
- vue.js - Vue 模板 - 将返回的文本字符串中找到的任何 URL 制作为链接