Stack Overflow 上一个帖子提到,当使用 Streamlit 的 Slider 修改 Bokeh 图表数据时,页面会滚动回到顶部。这是因为调整滑块时整个页面会重新加载。
另一位网友提供了一个解决方案,实际上是在 Bokeh 内部提供了原生的 HTML Slider,效果确实非常流畅。
关于这个帖子,可以通过这个链接访问:Streamlit slider will refresh the whole page and go to the top
但是使用 Streamlit Slider 的初衷是希望能够利用 Python 快速构建应用。我非常喜欢 Streamlit,但有时会遇到类似的问题,比如页面会重新加载,即使我们只修改了页面上的一点内容。所以有没有办法在Bokeh外部创建一个 slider 或者其它组件来控制 Bokeh 图表?
这里提供用 SimpleStart 的解决方案,先看效果:
主要的步骤是
1. 先实现 Bokeh 部分的图表,其中source 部分命名一个名字,以便后续能找到并修改。
2. 用 ss.htmlview 加载 Bokeh 图表
3. 创建一个 ss.slider
4. 在 ss.slider 滑动事件中通过一小段 javascript 去修改Bokeh中的数据
代码参考
import simplestart as ss
from bokeh.plotting import figure
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.resources import CDN
from bokeh.embed import file_html, components
### ui
ss.write('# Bernoulli Distribution Visualization')
def plot(p=0.5):
x = [0, 1]
y = [1 - p, p]
colors = ['#1f77b4', '#ff7f0e']
source = ColumnDataSource(data=dict(x=x, y=y, color=colors))
source.name = "mysource"
fig = figure(
title="Bernoulli Distribution",
x_axis_label="Outcome",
y_axis_label="Probability",
)
fig.title.align = "center"
fig.vbar(x="x", top="y", width=0.5, color="color", source=source)
return file_html(fig, CDN, "Bernoulli Distribution")
ss.htmlview(plot())
def change_value(value):
js = f'''
const iframe = document.getElementById('myIframe');
const innerWindow = iframe.contentWindow;
const bokehDoc = iframe.contentWindow.Bokeh.documents[0];
const source = bokehDoc.get_model_by_name("mysource");
//console.log("source", source)
// updata source data
var value = {value};
source.data['y'] = [1 - value, parseFloat(value)];
source.change.emit();
'''
return js
def slider_change(event):
ss.exec_js(change_value(event.value))
ss.slider('Probability of Success \(p\)', 0.0, 1.0, 0.5, onchange=slider_change, triggerOnUpdate = True)