Bokeh Python 如何与单选按钮交互

Bokeh Python how to interact with radio buttons

我构建了一个顶部带有单选按钮组的散点图。我如何 link 带有情节的小部件?我想要达到的结果如下:

选择 'one' - 只显示 x 值等于 1 的点

选择 'two' - 只显示 x 值等于 2 的点

选择 'three' - 只显示 x 值等于 3 的点

到目前为止,这是我的代码:

dataset = {'x':[0,1,2],'y':[0,1,2]}

source2 = ColumnDataSource(data=dataset)


p2 = figure(plot_width=600, plot_height=600, 
            x_range=(-0.1, 2.1), y_range=(-0.1,2.1))

p2.scatter('x', 'y', source=source2, 
          size=15,
          alpha=0.8, 
          line_color=None)

# option
option = RadioButtonGroup(labels=["One", "Two", "Three"], active=0)


show(column(option, p2))

这正是您想要的:

from bokeh.io import show
from bokeh.models import ColumnDataSource,
from bokeh.plotting import figure
from bokeh.models.widgets import RadioButtonGroup
from bokeh.layouts import column, widgetbox
from bokeh.models.callbacks import CustomJS

dataset = {'x':[0,1,2],'y':[0,1,2],'x_filter':[0,1,2]}

source = ColumnDataSource(data=dataset)
p = figure(plot_width=600, plot_height=600, 
            x_range=(-0.1, 2.1), y_range=(-0.1,2.1))
p.scatter('x', 'y', source=source, 
          size=15, alpha=0.8, line_color=None)

# add callback to control 
callback = CustomJS(args=dict(p=p, source=source), code="""

            var radio_value = cb_obj.active;
            var data = source.data;            
            x = data['x']
            x_filter = data['x_filter']
            y = data['y']

            for (i = 0; i < x.length; i++) {
                if(x_filter[i] == radio_value) {
                    x[i] = x_filter[i];
                } else {
                    x[i] = undefined;
                }
            }
        source.change.emit();
        """)

# option
option = RadioButtonGroup(labels=["One", "Two", "Three"],
                          active=0, callback=callback)
show(column(widgetbox(option),p))

有趣的代码在JavaScript中。基本上,它会检查每个点的 x 坐标是否等于您的 RadioButton 选择。如果没有,则该点设置为缺失。这使得该点在情节中消失。新列 x_filter 已添加到您的数据中。它用于将 Radio 选择与您的原始 x 进行比较。实际的x用于绘图。