在散景中创建一个简单的范围滑块
范围滑块小部件允许您从带有起点和终点的滑块中选择浮点范围。散景小部件 RangeSlider 由开始和结束值、步长、初始值和标题组成。
句法:
range_slider = RangeSlider(start, end, value, step, title)
range_slider.js_on_change(“value”, CustomJS(code))
让我们看看创建范围滑块的过程。
- 从 bokeh.models 导入 RangeSlider 小部件
在这一步中,我们从 bokeh.plotting 界面导入图形和显示方法。 Bokeh.plotting 界面允许您通过组装各种元素(如网格、轴和其他工具)来创建绘图。 figure() 方法允许您将不同类型的字形添加到绘图中,而 show() 方法允许您在浏览器中显示您的可视化。同样,我们从 bokeh.layouts 导入布局来创建布局对象。最后,我们导入 RangeSlider 来创建范围滑块并使我们的可视化交互。
- 设置数据和图形。
在这一步中,我们将创建一个输出文件,它是一个 HTML 文件,并在浏览器的新窗口中打开。输出将显示在此 HTML 文件中。 figure 方法创建一个具有给定范围、高度和宽度的图形。
- 创建一个 RangeSlider 对象
Syntax:
RangeSlider(title, start, end, step, value)
Parameter:
- Title: It represents the title of the range slider.
- Start: It represents the range’s lower bound and is of type float.
- end: It represents the range’s upper bound and is of type float.
- step: It represents the interval between the values and is of type float.
- value: It represents a tuple that contains the values of upper and lower bounds of the selected range.
- 链接到 JavaScript
javaScript 的链接是通过使用 link_js()函数将 RangeSlider 生成的值链接到您的绘图来提供的。
句法:
RangeSliderObject.js_link(value, p.x_range, start/end, attr_selector)
- 创建要在浏览器上显示的所有元素的布局。
最后,我们使用 layout 方法显示仪表板的所有元素,并使用 show(layout) 在浏览器中显示我们的布局。
程序:
Python
from bokeh.plotting import figure, show
from bokeh.layouts import layout
from bokeh.models import RangeSlider
x = list(range(12))
y = [i**2 for i in x]
output_file = ('range_slider.html')
p = figure(x_range=(1, 9), plot_width=600, plot_height=300)
points = p.circle(x=x, y=y, size=40, fill_color="red")
range_slider = RangeSlider(
title=" Adjust X-Axis range",
start=0,
end=12,
step=1,
value=(p.x_range.start, p.x_range.end),
)
range_slider.js_link("value", p.x_range, "start", attr_selector=0)
range_slider.js_link("value", p.x_range, "end", attr_selector=1)
layout = layout([range_slider], [p])
show(layout)
输出: