添加小部件

widget是可以添加到Bokeh应用程序中的交互式控件,为可视化提供前端用户界面。它们可以驱动新的计算,更新绘图,并连接到其他编程功能。当与Bokeh服务器一起使用时,小部件可以运行任意Python代码,从而支持复杂的应用程序。小部件也可以通过浏览器的Javascript运行时在独立的HTML文档中使用而不需要Bokeh服务器。

回调

要使用小部件,必须将它们添加到文档中并定义它们的回调。小部件可以直接添加到文档根目录或嵌套在布局中。有两种方法可以使用小部件的功能:

  • A CustomJS 回调(请参见 JavaScript回调 ). 这种方法可以在独立的HTML文档或Bokeh服务器应用程序中工作。

  • 使用 bokeh serve 启动Bokeh服务器并使用设置事件处理程序 .on_change (或者对于一些小部件, .on_click

事件处理程序是用户可以附加到小部件上的Python函数。当小部件上的某些属性发生更改时,将调用这些函数。事件处理程序的函数签名取决于它们如何附加到小部件(例如 .on_change.on_click

所有小工具都有 .on_change 方法,它将属性名和一个或多个事件处理程序作为参数。函数应该具有这些签名, (attr, old, new) 在哪里 attr 引用已更改属性的名称,并且 oldnew 请参考属性的先前值和更新值。

def my_text_input_handler(attr, old, new):
    print("Previous label: " + old)
    print("Updated label: " + new)

text_input = TextInput(value="default", title="Label:")
text_input.on_change("value", my_text_input_handler)

此外,一些小部件(包括按钮、下拉列表和复选框)具有 .on_click 方法,它将事件处理程序作为其唯一参数。为了一个平原 Button ,调用此处理程序时不带参数。与其他控件一起使用 .on_click ,则向处理程序传递新的属性值。

def my_radio_handler(new):
    print 'Radio button option ' + str(new) + ' selected.'

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(my_radio_handler)

Bokeh提供了一组简单的默认小部件。用户可以创建自己的自定义小部件,或通过创建自定义扩展来包装不同的第三方小部件库,如中所述 扩展Bokeh .

有关要监视的属性的详细信息,请使用 .on_change参考文献 . (有关小部件的信息可在下面找到 bokeh.models

实例

下面的部分收集了使用所有内置小部件的简短但完整的示例。许多示例打印的输出可以通过查看浏览器Javascript控制台日志来观察。

纽扣

Bokeh提供了一个简单的按钮:

from bokeh.io import show
from bokeh.models import Button, CustomJS

button = Button(label="Foo", button_type="success")
button.js_on_click(CustomJS(code="console.log('button: click!', this.toString())"))

show(button)

CheckboxButtonGroup

Bokeh还提供了一个复选框按钮组,可以同时选择多个选项:

from bokeh.io import show
from bokeh.models import CheckboxButtonGroup, CustomJS

LABELS = ["Option 1", "Option 2", "Option 3"]

checkbox_button_group = CheckboxButtonGroup(labels=LABELS, active=[0, 1])
checkbox_button_group.js_on_click(CustomJS(code="""
    console.log('checkbox_button_group: active=' + this.active, this.toString())
"""))

show(checkbox_button_group)

CheckboxGroup

标准A复选框:

from bokeh.io import show
from bokeh.models import CheckboxGroup, CustomJS

LABELS = ["Option 1", "Option 2", "Option 3"]

checkbox_group = CheckboxGroup(labels=LABELS, active=[0, 1])
checkbox_group.js_on_click(CustomJS(code="""
    console.log('checkbox_group: active=' + this.active, this.toString())
"""))

show(checkbox_group)

ColorPicker

允许用户指定RGB颜色值的小部件。

from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import ColorPicker
from bokeh.plotting import Figure

plot = Figure(x_range=(0, 1), y_range=(0, 1), plot_width=350, plot_height=350)
line = plot.line(x=(0,1), y=(0,1), color="black", line_width=4)

picker = ColorPicker(title="Line Color")
picker.js_link('color', line.glyph, 'line_color')

show(column(plot, picker))

DataTable

Bokeh提供了一个基于SlickGrid的复杂的数据表小部件。请注意,由于表配置了一个数据源对象,因此共享此数据源的任何绘图都将自动在绘图和表之间链接选择(即使在静态HTML文档中也是如此)。

from datetime import date
from random import randint

from bokeh.io import show
from bokeh.models import ColumnDataSource, DataTable, DateFormatter, TableColumn

data = dict(
        dates=[date(2014, 3, i+1) for i in range(10)],
        downloads=[randint(0, 100) for i in range(10)],
    )
source = ColumnDataSource(data)

columns = [
        TableColumn(field="dates", title="Date", formatter=DateFormatter()),
        TableColumn(field="downloads", title="Downloads"),
    ]
data_table = DataTable(source=source, columns=columns, width=400, height=280)

show(data_table)

DatePicker

允许用户指定日期值的小部件。

from bokeh.io import show
from bokeh.models import CustomJS, DatePicker

date_picker = DatePicker(title='Select date', value="2019-09-20", min_date="2019-08-01", max_date="2019-10-30")
date_picker.js_on_change("value", CustomJS(code="""
    console.log('date_picker: value=' + this.value, this.toString())
"""))

show(date_picker)

DateRangeSlider

Bokeh日期范围滑块可以配置为 startend 日期值,a step 初始大小,一个 value 和A title

from datetime import date

from bokeh.io import show
from bokeh.models import CustomJS, DateRangeSlider

date_range_slider = DateRangeSlider(value=(date(2016, 1, 1), date(2016, 12, 31)),
                                    start=date(2015, 1, 1), end=date(2017, 12, 31))
date_range_slider.js_on_change("value", CustomJS(code="""
    console.log('date_range_slider: value=' + this.value, this.toString())
"""))

show(date_range_slider)

迪夫

一个小部件,用于在<div>标记中显示支持HTML的文本:

from bokeh.io import show
from bokeh.models import Div

div = Div(text="""Your <a href="https://en.wikipedia.org/wiki/HTML">HTML</a>-supported text is initialized with the <b>text</b> argument.  The
remaining div arguments are <b>width</b> and <b>height</b>. For this example, those values
are <i>200</i> and <i>100</i>, respectively.""",
width=200, height=100)

show(div)

FileInput

允许用户选择文件并存储其内容的小部件。

from bokeh.io import show
from bokeh.models import FileInput

file_input = FileInput()

show(file_input)

MultiChoice

在紧凑的水平布局中显示多个可用选项的多选控件:

from bokeh.io import show
from bokeh.models import CustomJS, MultiChoice

OPTIONS = ["foo", "bar", "baz", "quux"]

multi_choice = MultiChoice(value=["foo", "baz"], options=OPTIONS)
multi_choice.js_on_change("value", CustomJS(code="""
    console.log('multi_choice: value=' + this.value, this.toString())
"""))

show(multi_choice)

MultiSelect

在垂直列表中显示多个可用选项的多选控件:

from bokeh.io import show
from bokeh.models import CustomJS, MultiSelect

OPTIONS = [("1", "foo"), ("2", "bar"), ("3", "baz"), ("4", "quux")]

multi_select = MultiSelect(value=["1", "2"], options=OPTIONS)
multi_select.js_on_change("value", CustomJS(code="""
    console.log('multi_select: value=' + this.value, this.toString())
"""))

show(multi_select)

段落

用于在HTML<p>标记中显示文本块的小部件:

from bokeh.io import show
from bokeh.models import Paragraph

p = Paragraph(text="""Your text is initialized with the 'text' argument.  The
remaining Paragraph arguments are 'width' and 'height'. For this example, those values
are 200 and 100, respectively.""",
width=200, height=100)

show(p)

PasswordInput

模糊输入的文本:

from bokeh.io import show
from bokeh.models import CustomJS, PasswordInput

password_input = PasswordInput(placeholder="enter password...")
password_input.js_on_change("value", CustomJS(code="""
    console.log('password_input: value=' + this.value, this.toString())
"""))

show(password_input)

PreText

用于在HTML<pre>标记中显示预格式化文本块的小部件:

from bokeh.io import show
from bokeh.models import PreText

pre = PreText(text="""Your text is initialized with the 'text' argument.

The remaining Paragraph arguments are 'width' and 'height'. For this example,
those values are 500 and 100, respectively.""",
width=500, height=100)

show(pre)

RadioButtonGroup

单选按钮组一次最多可以有一个选定的按钮:

from bokeh.io import show
from bokeh.models import CustomJS, RadioButtonGroup

LABELS = ["Option 1", "Option 2", "Option 3"]

radio_button_group = RadioButtonGroup(labels=LABELS, active=0)
radio_button_group.js_on_click(CustomJS(code="""
    console.log('radio_button_group: active=' + this.active, this.toString())
"""))

show(radio_button_group)

RadioGroup

单选组使用标准单选按钮外观:

from bokeh.io import show
from bokeh.models import CustomJS, RadioGroup

LABELS = ["Option 1", "Option 2", "Option 3"]

radio_group = RadioGroup(labels=LABELS, active=0)
radio_group.js_on_click(CustomJS(code="""
    console.log('radio_group: active=' + this.active, this.toString())
"""))

show(radio_group)

RangeSlider

Bokeh范围滑块可以配置为 startend 值,a step 初始大小,一个 value 和A title

from bokeh.io import show
from bokeh.models import CustomJS, RangeSlider

range_slider = RangeSlider(start=0, end=10, value=(1,9), step=.1, title="Stuff")
range_slider.js_on_change("value", CustomJS(code="""
    console.log('range_slider: value=' + this.value, this.toString())
"""))

show(range_slider)

选择

单个选择小部件:

from bokeh.io import show
from bokeh.models import CustomJS, Select

select = Select(title="Option:", value="foo", options=["foo", "bar", "baz", "quux"])
select.js_on_change("value", CustomJS(code="""
    console.log('select: value=' + this.value, this.toString())
"""))

show(select)

滑块

Bokeh滑块可以配置为 startend 值,a step 初始大小,一个 value 和A title

from bokeh.io import show
from bokeh.models import CustomJS, Slider

slider = Slider(start=0, end=10, value=1, step=.1, title="Stuff")
slider.js_on_change("value", CustomJS(code="""
    console.log('slider: value=' + this.value, this.toString())
"""))

show(slider)

旋转器

数字微调器小部件:

import numpy as np

from bokeh.io import show
from bokeh.layouts import column, row
from bokeh.models import Spinner
from bokeh.plotting import figure

x = np.random.rand(10)
y = np.random.rand(10)

p = figure(x_range=(0, 1), y_range=(0, 1))
points = p.scatter(x=x, y=y, size=4)

spinner = Spinner(title="Glyph size", low=1, high=40, step=0.5, value=4, width=80)
spinner.js_link('value', points.glyph, 'size')

show(row(column(spinner, width=100), p))

制表符

选项卡窗格允许在可选选项卡中显示多个绘图或布局:

from bokeh.io import show
from bokeh.models import Panel, Tabs
from bokeh.plotting import figure

p1 = figure(plot_width=300, plot_height=300)
p1.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
tab1 = Panel(child=p1, title="circle")

p2 = figure(plot_width=300, plot_height=300)
p2.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=3, color="navy", alpha=0.5)
tab2 = Panel(child=p2, title="line")

show(Tabs(tabs=[tab1, tab2]))

TextAreaInput

用于从用户处收集多行文本的小部件:

from bokeh.io import show
from bokeh.models import CustomJS, TextAreaInput

text_area_input = TextAreaInput(value="default", rows=6, title="Label:")
text_area_input.js_on_change("value", CustomJS(code="""
    console.log('text_area_input: value=' + this.value, this.toString())
"""))

show(text_area_input)

TextInput

从用户处收集一行文本的小部件:

from bokeh.io import show
from bokeh.models import CustomJS, TextInput

text_input = TextInput(value="default", title="Label:")
text_input.js_on_change("value", CustomJS(code="""
    console.log('text_input: value=' + this.value, this.toString())
"""))

show(text_input)

ToggleButton

切换按钮保持打开/关闭状态:

from bokeh.io import show
from bokeh.models import CustomJS, Toggle

toggle = Toggle(label="Foo", button_type="success")
toggle.js_on_click(CustomJS(code="""
    console.log('toggle: active=' + this.active, this.toString())
"""))

show(toggle)