Bokeh Widget切片数据

时间:2017-05-19 07:30:39

标签: javascript python visualization bokeh

我正在尝试使用散景创建一个情节,以便在IPython Notebook上显示我的数据。我想添加一些小部件以使其更具交互性。以下是代码示例。

from bokeh.models import CustomJS, ColumnDataSource
from bokeh.plotting import Figure, output_notebook, show
from bokeh.models.widgets import Select
from bokeh.layouts import column

output_notebook()

x = [x*0.005 for x in range(0, 200)]
y = x
z = ['A' if i>50 else 'B' for i in range(len(x))]

source = ColumnDataSource(data=dict(x=x, y=y, z=z))

plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

def callback(source=source):
    data=source.get('data')
    f = cb_obj.get('value')
    x, y, z = data['x'], data['y'], data['z']
    x = [x[i] for i in range(len(x)) if z[i] == f]
    y = [y[i] for i in range(len(y)) if z[i] == f]
    z = [z[i] for i in range(len(z)) if z[i] == f]
    source.trigger('change')

slides = Select(title="Option:", value = 'A', options=['A', 'B'], 
                callback=CustomJS.from_py_func(callback))

layout = column(slider,plot)

show(layout)

enter image description here

我想这样做,如果我选择其他选项,则绘图将根据我在回调函数中指定的条件进行相应更改。关于为什么代码不起作用的任何建议?

P.S。我使用了这里的代码,但我更改了小部件,因为我遇到的问题类似于上面的http://bokeh.pydata.org/en/0.11.1/docs/user_guide/interaction.html#customjs-with-a-python-function

1 个答案:

答案 0 :(得分:0)

问题是您实际上并未更改数据[' x'],数据[' y']或数据[' z']的内容。

第二个问题是,如果您更改源数据,则无法将其更改回来,因为它不再包含您开始使用的完整数据。 解决方法是将原始数据传递给回调,并将过滤后的数据分配给ColumnDataSource,而不更改原始数据。

from bokeh.models import CustomJS, ColumnDataSource
from bokeh.plotting import Figure, output_notebook, show
from bokeh.models.widgets import Select
from bokeh.layouts import column

output_notebook()

x = [x*0.005 for x in range(0, 200)]
y = x
z = ['A' if i>50 else 'B' for i in range(len(x))]

original_source = ColumnDataSource(data=dict(x=x, y=y, z=z))
source = ColumnDataSource(data=dict(x=x, y=y, z=z))

plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

def callback(source=source, original_source = original_source):
    data=original_source.data
    s_data = source.data
    f = cb_obj.value
    x, y, z = data['x'], data['y'], data['z']
    x = [x[i] for i in range(len(x)) if z[i] == f]
    y = [y[i] for i in range(len(y)) if z[i] == f]
    z = [z[i] for i in range(len(z)) if z[i] == f]
    s_data['x'] = x
    s_data['y'] = y
    s_data['z'] = z
    source.trigger('change')

slides = Select(title="Option:", value = 'A', options=['A', 'B'], 
                callback=CustomJS.from_py_func(callback))

layout = column(slides,plot)

show(layout)