How to get a list of Bokeh widget events and attributes (which can be used to trigger a Python callback)

M4u*_*ice 5 python bokeh

The real (general) question

I am new to Bokeh and I am trying to build a plot which can be dynamically updated based on input provided by a widget. However, usage of Python callbacks is not thoroughly documented for most widgets and therefore I'm stuck.

  1. How can I know which widget method I should use to attach my callback? I can guess the available choices by probing the widgets attributes in an interactive console, but that's not elegant and I'm sure it's written somewhere in the documentation.
  2. Provided that I would know about the method to use (e.g. on_event or on_change), I still have to figure out its signature and arguments. For instance, if I'm using on_change, which widget attributes can I monitor?
  3. Once I know which attribute I can monitor, how can I know the data structure which will be yielded by the event?

Some more context and the (not-as-useful) specific question

Here is an appropriate example. I am using a notebook-embedded server like in this example. As an exercise, I would like to replace the slider with a DataTable with arbitrary values. Here is the code I currently have:

from bokeh.layouts import column
from bokeh.models import ColumnDataSource, DataTable
from bokeh.plotting import figure
from bokeh.io import show, output_notebook

from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature

output_notebook()

def modify_doc(doc):
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)
    source_table = ColumnDataSource(data={"alpha": [s for s in "abcdefgh"], 
                                          "num": list(range(8))})

    plot = figure(x_axis_type='datetime', y_range=(0, 25),
                  y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        # This is the old callback from the example. What is "new" when I use 
        # a table widget?
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = ColumnDataSource(data=data).data

    table = DataTable(source=source_table, 
                      columns=[TableColumn(field="alpha", title="Alpha"),
                               TableColumn(field="num", title="Num")])
    # How can I attach a callback to table so that the plot gets updated 
    # with the "num" value when I select a row?
    # table.on_change("some_attribute", callback)

    doc.add_root(column(table, plot))

show(modify_doc)
Run Code Online (Sandbox Code Playgroud)

Ton*_*ony 6

该答案是针对Bokeh v1.0.4给出的,可能与最新文档不兼容

JavaScript回调Python回调是Bokeh中非常强大的工具,可以附加到任何Bokeh模型元素。另外,您可以通过使用TypeScript编写自己的扩展来扩展Bokeh功能(最终编译为JS)

可以使用以下两种方法之一添加JS回调:

Model.js_on_event('event', callback)
Model.js_on_change('attr', callback)
Run Code Online (Sandbox Code Playgroud)

Python回调主要用于小部件:

Widget.on_event('event, onevent_handler)
Widget.on_change('attr', onchange_handler)
Widget.on_click(onclick_handler)
Run Code Online (Sandbox Code Playgroud)

每个小部件的事件处理程序的确切函数签名可以是:

onevent_handler(event)
onchange_handler(attr, old, new) 
onclick_handler(new)
onclick_handler()
Run Code Online (Sandbox Code Playgroud)

attr可以是任何部件类(或它的基类)属性。因此,您始终需要查阅Bokeh参考页。还扩大了JSON原型有助于找出哪些属性的支持如寻找事业部,我们不能直接看到idnamestyletext属性,这来源于其基类。但是,所有这些属性都存在于Div的JSON原型中,因此受Div支持:

{
  "css_classes": [],
  "disabled": false,
  "height": null,
  "id": "32025",
  "js_event_callbacks": {},
  "js_property_callbacks": {},
  "name": null,
  "render_as_text": false,
  "sizing_mode": "fixed",
  "style": {},
  "subscribed_events": [],
  "tags": [],
  "text": "",
  "width": null
}
Run Code Online (Sandbox Code Playgroud)

回到您的问题:很多时候,您可以使用不同的方法获得相同的结果。

据我所知,没有一种很好的方法可以列出每个小部件的所有受支持的事件,但是阅读文档并深入研究基类会有所帮助。

使用上述方法,可以检查可以在回调中使用的窗口小部件属性。当涉及到事件时,我建议您bokeh.events在IDE中查看和探索该类。您可以在其中找到每个事件的扩展说明。随着程序员的直觉选择小部件支持的正确事件,随着时间的流逝自然会自然而然地发生(因此,没有理由button_clickPlot也没有pan事件,Button反之亦然)。

决定将回调附加到哪个小部件(模型元素)以及要选择哪种方法或绑定到哪个事件的回调取决于您,并且主要取决于:哪个用户操作应触发您的回调?

因此,您可以将JS回调附加到任何小部件(值更改,滑块移动等),任何工具(TapTool,HoverTool等),data_source(单击字形),绘制画布(例如单击)在字形以外的区域)或绘图范围(缩放或平移事件)等。

基本上,您需要了解所有Python对象在BokehJS中都有它们的等效项,因此您可以在两个域中以相同的方式使用它们(当然,在语法上有所不同)。

例如,此文档显示ColumnDataSource具有“ selected”属性,因此对于点,您可以检查source.selected.indices并查看选择了绘图上的哪个点或在您的情况下喜欢:选择了哪些表行。您可以在Python和浏览器中的代码中设置断点,并检查Python或BokehJS数据结构。在运行代码时,可以将环境变量BOKEH_MINIFIED设置no为在IDE(运行配置)中或在终端(例如BOKEH_MINIFIED=no python3 main.py)中。这将使在浏览器中调试BokehJS更加容易。

这是您的代码(由于未安装Jupiter Notebook,因此对“ pure Bokeh” v1.0.4做了一些修改)

from bokeh.layouts import column
from bokeh.models import ColumnDataSource, DataTable, TableColumn
from bokeh.plotting import figure, curdoc
from bokeh.io import show, output_notebook
from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature

# output_notebook()
def modify_doc(doc):
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data = df)
    source_table = ColumnDataSource(data = {"alpha": [s for s in "abcdefgh"],
                                            "num": list(range(8))})

    plot = figure(x_axis_type = 'datetime', y_range = (0, 25),
                  y_axis_label = 'Temperature (Celsius)',
                  title = "Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source = source)

    def callback(attr, old, new):  # here new is an array containing selected rows
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new[0])).mean()  # asuming one row is selected

        source.data = ColumnDataSource(data = data).data

    table = DataTable(source = source_table,
                      columns = [TableColumn(field = "alpha", title = "Alpha"),
                                 TableColumn(field = "num", title = "Num")])
    source_table.selected.on_change('indices', callback)

    doc().add_root(column(table, plot))

modify_doc(curdoc)
# show(modify_doc)
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明