Hi, Im trying to plot some data and use Select widget to filter the data in jupyter notebook. What is the best approach? I google a lot and found CustomJs, ipywidget ( in bokeh wiki recommend this), also found solutions with CDSView and callbacks.
I would prefer using only python an minimal javascript. Im practising using de iris dataset but I can’t make it work. Also, Im not able to add a ‘All’ value to remove the filter.
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, Select
from bokeh.plotting import figure, output_file, show
from bokeh.io import output_notebook
import seaborn as sns
output_notebook()
df = sns.load_dataset('iris')
source = ColumnDataSource(data=df)
true_source = ColumnDataSource(data=df)
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
Columns = [TableColumn(field=c, title=c) for c in df.columns] # bokeh columns
data_table = DataTable(columns=Columns, source=ColumnDataSource(df), width=800, height=280)
show(data_table)
from bokeh.models import CDSView, ColumnDataSource, IndexFilter
import pandas as pd
callback = CustomJS(args=dict(source=source,ts=true_source), code='''
var d1=ts.data;
var d2=source.data;
var f=cb_obj.value;
var x_2=[];
var y_2=[];
var sepal_lenght_2=[];
var sepal_width_2=[];
for(var i=0; i<d1['species'].length; i++){
if(d1['species'][i]==f){
x_2.push(d1['petal_lenght'][i]);
y_2.push(d1['petal_width'][i]);
sepal_lenght_2.push(d1['sepal_lenght'][i]);
sepal_width_2.push(d1['sepal_width'][i]);
}
}
d2['x']=x_2;
d2['y']=y_2;
d2['sepal_lenght']=sepal_lenght_2;
d2['sepal_width']=sepal_width_2;
source.change.emit();
''')
colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
colors = [colormap[x] for x in df['species']]
p = figure(title="Iris Morphology")
p.xaxis.axis_label = 'Petal Length'
p.yaxis.axis_label = 'Petal Width'
colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
colors = [colormap[x] for x in df['species']]
select = Select(title="Option:", value='setosa', options=df.species.unique().tolist())
select.js_on_change("value",callback)
p.scatter(x='petal_length', y='petal_width', source=source)
show(column(select, p))
Any help is welcome.
Regards.
Sebastian.