我试图创建滑块,当你拖动滑块时,显示的图形部分只是滑块上的部分。例如,如果您查看下面的图表,如果滑块设置为1990,您将只看到1990年到2016年的行。我找到了plotly的工作示例,但我想知道它是否可以完成了散景。
到目前为止,这是我的代码:
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))
这会渲染一个滑块,但它没有做任何事情,我不知道从哪里开始。
答案 0 :(得分:1)
您的回调代码存在一些问题。例如:
i
从0
循环到s_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
不是必需的toolbar_location='above'
中添加figure(...)
以避免与图例冲突column
中,然后再添加到右侧情节等...)