使用带有滑块的 CustomJS 回调绘制不同的列

Plotting different column using CustomJS callbacks with slider

我有一个包含多列的简单 ColumnDataSource,每一列代表模拟的不同日期,每一行代表状态为 a、b、c 等的实体数。我希望能够用滑块擦洗天(列)。

我已经查看了 1, 2, and the Bokeh docs 以获取信息,但我无法成功使其正常工作。我有以下代码(最小):

from bokeh.plotting import figure
from bokeh.layouts import column, widgetbox
from bokeh.models import CustomJS, Slider, ColumnDataSource, ranges
from bokeh.io import output_file, show

output_file("barplot.html")
sim_time=4

data = {'x': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
        '0': [2860.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        '1': [2860.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        '2': [0.0, 2860.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        '3': [0.0, 2860.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}

source = ColumnDataSource(data)

barplot = figure(plot_width=800, plot_height=600, tools='pan', x_axis_label='Status', x_range=source.data['x'], y_range=ranges.Range1d(start=0, end=3000))
barplot.vbar(source=source, x='x', top='0', width=0.6)

callback = CustomJS(args={'source':source}, code="""
    console.log(' changed selected time', cb_obj.value);
    var data = source.data;
    data['0'] = data[cb_obj.value];
    source.change.emit()
""")

time_slider = Slider(start=0, end=sim_time-1, value=1, step=1, callback=callback)
callback.args["time"] = time_slider

show(column(barplot, time_slider))

即我无法使用滑块浏览各列。

我做错了什么?

干杯

试试这个:

data = {'x': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
        'y': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        '0': [0.0, 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, 0.0],
        '1': [0.0, 1000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        '2': [0.0, 0.0, 1000.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        '3': [0.0, 0.0, 0.0, 1000.0, 0.0, 0.0, 0.0, 0.0]}

source = ColumnDataSource(data)

barplot = figure(plot_width=800, plot_height=600, tools='pan',
                 x_axis_label='Status', x_range=source.data['x'],
                 y_range=ranges.Range1d(start=0, end=3000))
barplot.vbar(source=source, x='x', top='y', width=0.6)

callback = CustomJS(args=dict(source=source), code="""
    console.log(' changed selected time', cb_obj.value);
    var data = source.data;
    data['y'] = data[cb_obj.value];
    source.change.emit()
""")

time_slider = Slider(start=0, end=sim_time-1, value=0, step=1, callback=callback)
callback.args["time"] = time_slider    
show(column(barplot, time_slider))

您的代码有两个问题。 0 12 3 的条形是相同的。您不会看到选择 2 和 3 之间有任何变化。此外,您使用 0 列来存储数据。但是随后您在 JS 代码中覆盖了 0 中的数据。因此,数据会丢失。因此,在滑块上切换回 0 不会有任何效果。这就是为什么我向您的数据添加了一个新的(空)列 y。这只是一个占位符,用于绘制当前选定的数据。