我有一个关于在散景中使用 CustomJS 脚本更新数据的一般问题,当小部件触发回调时。下面的代码对我来说工作正常import numpy as npfrom bokeh.layouts import column, rowfrom bokeh.models import CustomJS, Sliderfrom bokeh.plotting import ColumnDataSource, figure, output_file, output_notebook, showoutput_notebook()# Define a slidermy_slider = Slider(start=0, end=2, value=0, step=1, title="Amplitude")# Produce a list of data to be scrolled with the sliderxy_list = []for a in range(0,3): x_list = np.linspace(0, 10, 500) y_list = float(a) * np.sin(x_list) xy_list.append( ColumnDataSource(data=dict(x=x_list, y=y_list)) )# Produce the initial data to be displayed# NOTE: this is like a hard-coded deepcopy,# since deepcopy doesn't seem to work well # with Bokeh objectsxy_current = ColumnDataSource( data=dict( x=np.linspace(0, 10, 500), y=0.0*np.linspace(0, 10, 500) ))# Produce a plotplot = figure(y_range=(-10, 10), plot_width=200, plot_height=200)plot.line('x', 'y', source=xy_current, line_width=3, line_alpha=0.6)# Define a callback for the slidercallback = CustomJS( args=dict(# source_0=xy_source_0, # An instance of ColumnDataSource source_curr=xy_current, # An instance of ColumnDataSource source_list=xy_list, # A list, with entries of type ColumnDataSource ), code=""" var data_curr = source_curr.data; // This is an instance of bokeh.core.property.wrappers.PropertyValueColumnData var plot_i = cb_obj.value // This is an int var old_x = data_curr['x'] // This is a numpy.ndarray var old_y = data_curr['y'] // This is a numpy.ndarray var new_x = source_list[plot_i].data['x'] // This is a numpy.ndarray var new_y = source_list[plot_i].data['y'] // This is a numpy.ndarray // Now update the y-values for each x, based on the slider value for (var i = 0; i < old_x.length; i++) { old_x[i] = new_x[i]; old_y[i] = new_y[i]; } source_curr.change.emit();""")我尝试这样做,但数据没有更新。有人可以解释为什么,以及如何实现这种更高的数据包变化(即不必逐个更改列表的值)?
1 回答
德玛西亚99
TA贡献1770条经验 获得超3个赞
首先,要纠正一个误解:
var old_x = data_curr['x'] // This is a numpy.ndarray
这是在NumPy不存在的浏览器中执行的JavaScript,因此它要么是JS类型数组,要么是普通的JS数组,但绝对不是.numpy.ndarray
您必须实际更新源中的值。当您执行以下操作时:
var old_x = data_curr['x']
创建新的局部变量。如果您随后执行以下操作:
old_x = new_x
然后,您所要做的就是为局部变量分配一个新值。这完全不会影响数据源。
相反,您需要类似的东西:
source_curr.data['x'] = new_x
这实际上修改了数据源的内容。
添加回答
举报
0/150
提交
取消