Bokeh - 過濾資料



通常,你可能想要獲取滿足特定條件的資料部分的 Plot,而不是整個資料集。在 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)

輸出

IndexFilter

若要僅從滿足特定布林條件的資料來源中選擇那些行,請應用 BooleanFilter。

一個典型的 Bokeh 安裝在 sampledata 目錄中包含了許多示例資料集。對於以下示例,我們使用以 unemployment1948.csv 形式提供的 unemployment1948 資料集。它儲存了自 1948 年以來美國每年的失業率百分比。我們只想為 1980 年及以後的年份生成 Plot。為此,透過對給定的資料來源應用 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)

輸出

BooleanFilter

為了在應用過濾器時增加靈活性,Bokeh 提供了一個 CustomJSFilter 類,藉助該類,可以透過使用者定義的 JavaScript 函式過濾資料來源。

下面給出的示例使用了相同的美國失業資料。定義一個 CustomJSFilter 來繪製 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)
廣告
© . All rights reserved.