Bokeh-filtering-data

提供:Dev Guides
移動先:案内検索

ボケ-データのフィルタリング

データセット全体ではなく、特定の条件を満たすデータの一部に関するプロットを取得したい場合がよくあります。 bokeh.modelsモジュールで定義されたCDSViewクラスのオブジェクトは、1つ以上のフィルターを適用することにより、検討中のColumnDatasourceのサブセットを返します。

IndexFilterは、最も単純なタイプのフィルターです。 図のプロット中に使用するデータセットの行のみのインデックスを指定する必要があります。

次の例は、CDSViewをセットアップするためのIndexFilterの使用を示しています。 結果の図は、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年以降のプロットのみを生成します。 そのために、CDSViewオブジェクトは、指定されたデータソースにBooleanFilterを適用することによって取得されます。

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関数を使用してデータソースをフィルタリングできます。

以下の例では、同じUSA失業データを使用しています。 1980年以降の失業率をプロットするためのCustomJSFilterの定義。

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)