我使用 FastAPI 作为 Python 后端,并使用 Plotly 从一些数据生成绘图。在客户端我使用 HTMX。
服务器使用
Figure.to_html( full_html = False)
直接发送绘图的 HTML,HTMX 直接将其交换到页面中的正确位置。
这一切都非常方便且容易做到,但现在我需要在数据变化时实时更新绘图。因此,我使用 FastAPI 和 HTMX 的
ws
扩展设置了一个 websocket 连接,以便在需要时更新绘图。
问题是,如果我在每次更新数据时再次发送整个绘图,则整个绘图都会被 HTMX 交换,并且用户会丢失绘图的当前视图状态,即缩放率、平移位置等......
那么有没有一种方法可以更详细地了解从 Plotly 发送的内容?
我需要:
我该怎么做?有可能吗?
HTMX 除外(原理应该保持不变),我建议:
Python 后端提供初始页面:它包含一个具有特定 id 的空 div 包装器、初始数据以及用于使用 Plotly.js 创建/更新绘图的脚本:
后端发送实时数据(JSON)到客户端。
客户端将新数据追加到当前数据并相应地更新绘图(请参阅Plotly.js函数参考)
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-2.35.2.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
<script>
// Create graph with initial data
const gd = document.getElementById('myDiv');
const data = [{ /* ... */ }];
const layout = { /* ... */ };
Plotly.newPlot(gd, data, layout);
// Update graph when receiving new data
function onUpdate(newData) {
append(data, newData); // custom function, depends on data (plotly trace type)
Plotly.restyle(gd, data); // use Plotly.restyle to update data only
}
/* Logic for updating data (register `onUpdate`, define `append` etc.) ... */
</script>