Hello all,
I’m trying to show a data table linked with multi-choice widget. The goal is to only show the rows that matches the multi-choice. I’m not sure what I’m missing, it should work but it doesn’t. The selection doesn’t change the table.
code below:
from bokeh.models import ColumnDataSource, DataTable, TableColumn, CustomJS, MultiChoice
from bokeh.plotting import figure, show
import pandas as pd
import numpy as np
original_data = dict(species = ['A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','B','C','D','E','A','A'],
length = [2, 10, 20, 40, 60, 80, 70, 50, 15, 36, 76, 74, 72, 44, 36, 18, 40, 64, 40, 64, 40, 30, 120],
weight = [2, 100, 150, 200, 420, 700, 600, 300, 200, 200, 620, 610, 601, 610, 601, 80, 205, 80, 800, 700, 240, 160, 800],
set_number = ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '3', '4', '1', '5', '1'],
sex_id = [2, 0, 0, 0, 2, 1, 1, 0, 2, 1, 1, 1, 0, 1, 1, 0, 2, 1, 1, 2, 1, 0, 2])
df = pd.DataFrame(original_data)
field= [c for c in df.columns]
columns = []
for i in field:
columns.append(TableColumn(field=i,title=i))
source = ColumnDataSource(df)
table_source = ColumnDataSource(df.iloc[0:0])
table = DataTable(columns=columns,source=table_source)
options = list(df.species.unique())
multi_choice = MultiChoice(value=[], options=options, title='species:')
callback = CustomJS(args=dict(source=source, table_source=table_source,multi_choice=multi_choice,table=table), code="""
var s1 = source.data;
var s2 = table_source.data;
var selected = multi_choice.value;
var s2['species'] = [];
var s2['length'] = [];
var s2['weight'] = [];
var s2['set_number'] = [];
var s2['sex_id'] = [];
for (var i = 0; i < s1['species'].length; i++) {
if (selected.indexOf(s1['species'][i]) >= 0) {
s2['species'].push(s1['species][i])
s2['length'].push(s1['length'][i])
s2['weight'].push(s1['weight'][i])
s2['set_number'].push(s1['set_number'][i])
s2['sex_id'].push(s1['sex_id'][i])
}
}
table_source.change.emit();
table.change.emit();
""")
multi_choice.js_on_change('value', callback)
show(row(table,multi_choice))