Bokeh 筛选数据
通常情况下,你可能想获得一个与满足某些条件的部分数据有关的图,而不是整个数据集。在bokeh.models模块中定义的CDSView类的对象通过对其应用一个或多个过滤器返回所考虑的ColumnDatasource的一个子集。
IndexFilter是最简单的过滤器类型。你必须从数据集中指定那些你想在绘制图表时使用的行的索引。
下面的例子演示了如何使用IndexFilter来设置CDSView。结果图显示了ColumnDataSource的x和y数据系列之间的线状图形。通过对其应用索引过滤器得到一个视图对象。该视图被用来绘制IndexFilter的结果–圆形字形。
例子
from bokeh.models import ColumnDataSource, CDSView, IndexFilter
from bokeh.plotting import figure, output_file, show
source = ColumnDataSource(data = dict(x = list(range(1,11)), y = list(range(2,22,2))))
view = CDSView(source=source, filters = [IndexFilter([0, 2, 4,6])])
fig = figure(title = 'Line Plot example', x_axis_label = 'x', y_axis_label = 'y')
fig.circle(x = "x", y = "y", size = 10, source = source, view = view, legend = 'filtered')
fig.line(source.data['x'],source.data['y'], legend = 'unfiltered')
show(fig)
输出
要从数据源中只选择那些满足某个布尔条件的行,可以应用一个布尔过滤器。
一个典型的Bokeh安装由sampledata目录中的一些样本数据集组成。在下面的例子中,我们使用以 unemployment1948.csv形式提供的 unemployment1948数据集。它存储了自1948年以来美国各年的失业百分比。我们希望只生成1980年以来的图表。为此,通过对给定的数据源应用BooleanFilter来获得CDSView对象。
from bokeh.models import ColumnDataSource, CDSView, BooleanFilter
from bokeh.plotting import figure, show
from bokeh.sampledata.unemployment1948 import data
source = ColumnDataSource(data)
booleans = [True if int(year) >= 1980 else False for year in
source.data['Year']]
print (booleans)
view1 = CDSView(source = source, filters=[BooleanFilter(booleans)])
p = figure(title = "Unemployment data", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label='Percentage')
p.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2)
show(p)
输出
为了增加应用过滤器的灵活性,Bokeh提供了一个CustomJSF过滤器类,在它的帮助下,数据源可以用用户定义的JavaScript函数进行过滤。
下面的例子使用了相同的美国失业数据。定义一个CustomJSF过滤器来绘制1980年及以后的失业数字。
from bokeh.models import ColumnDataSource, CDSView, CustomJSFilter
from bokeh.plotting import figure, show
from bokeh.sampledata.unemployment1948 import data
source = ColumnDataSource(data)
custom_filter = CustomJSFilter(code = '''
var indices = [];
for (var i = 0; i < source.get_length(); i++){
if (parseInt(source.data['Year'][i]) > = 1980){
indices.push(true);
} else {
indices.push(false);
}
}
return indices;
''')
view1 = CDSView(source = source, filters = [custom_filter])
p = figure(title = "Unemployment data", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label = 'Percentage')
p.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2)
show(p)