2017-09-27 41 views
0

我试图创建滑块,当您拖动滑块时,显示的图形部分只是滑块上的内容。例如,如果你看下面的图表,如果滑块设置为1990,那么你只能看到从1990年到2016年的线条。我发现了一个plotly的实例,但我想看看它是否可以用Bokeh完成。 enter image description here使用rangeslider创建时间序列图

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

p = figure(width = 900, height = 450) 
p.xaxis.axis_label = 'Year' 
p.yaxis.axis_label = 'Aggregated Number of Degrees in Education' 

source = ColumnDataSource(df) 
fill_source = ColumnDataSource(data=dict(x=[],y=[])) 

# Create objects for each line that will be plotted 
stem = p.line('year', 'stem', line_color='#8dd3c7', line_width=3, source=source) 
stem = p.circle('year', 'stem', line_color='#8dd3c7', line_width=3, source=source) 
sped = p.line('year', 'sped', line_color='#fdb462', line_width=3, source=source) 
elem = p.line('year', 'elem', line_color='#bebada', line_width=3, source=source) 
elem = p.square('year', 'elem', line_color='#bebada', line_width=3, source=source) 
other = p.line('year', 'other', line_color='#fb8072', line_width=4, source=source) 
aggtotal = p.line('year', 'aggtotal', line_dash=[4,4,], line_color='#80b1d3', line_width=3, source=source) 

yaxis = p.select(dict(type=Axis, layout="left"))[0] 
yaxis.formatter.use_scientific = False  
legend = Legend(items=[("STEM", [stem]) 
         ,("SPED" , [sped]) 
         ,("Elementary", [elem]) 
         ,("Other", [other]) 
         ,("Total Education Graduates", [aggtotal])], location=(0, 0)) 
p.add_tools(HoverTool(tooltips=[("Date", "@year")])) 
p.add_layout(legend, 'right')  

callback_test = CustomJS(args=dict(source=source,fill_source=fill_source), code=""" 
var data = source.data; 
var fill_data = fill_source.data; 
var s_val = cb_obj.value; 
fill_data['x']=[]; 
fill_data['y']=[]; 
for (i = 0; i < s_val; i++) { 
    fill_data['y'][i].push(data['y'][i]); 
    fill_data['x'][i].push(data['x'][i]);   
    } 
fill_source.trigger('change'); 
""") 

sped_slider = Slider(start=1984, end= 2016, value=1, step=1,title="Year",callback=callback_test) 
callback_test.args["sped"] = sped_slider 
layout = row(p,widgetbox(sped_slider)) 

这使得滑块,但它没有做任何事情,我不知道在哪里可以从这里走。

回答

1

您的回调代码存在一些问题。例如:

  • 你循环i0s_val(其可以是1990年),这是不与您的阵列的长度相一致。
  • 您字形引用列'stem',等等......但fill_source有列'x''y'
  • 您字形参考source作为源,但后来改变和fill_source触发事件。

所有这些都可能是固定的,但有一个更简单的方法,调整回调的范围。例如。取代您的回拨:

x_range = p.x_range 
callback_test = CustomJS(args=dict(x_range=x_range), code=""" 
    var start = cb_obj.value; 
    x_range.start = start; 
    x_range.change.emit(); 
""") 

请注意对事件触发器的更改。你的版本可以工作,但我认为它会被弃用。

另外:

  • 此行callback_test.args["sped"] = sped_slider是没有必要的
  • 您可以添加在figure(...)toolbar_location='above'为避免与传说
  • 你仍然会有滑块之间的布局冲突问题和可以以不同方式修复的图例(滑块下方或将滑块和图例插入到column之后再添加到绘图右侧等)。