Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Bokeh DataTable cell content on click?

Do you know how to get Bokeh DataTable cell value by clicking on it?

If I use:

data = dict(
 items=bokehItems,
    values0=bokehValues0,
    values1=bokehValues1,
    values2=bokehValues2
)

source = ColumnDataSource(data)

columns = [
    TableColumn(field="items", title="Item"),
    TableColumn(field="values0", title="Value"),
    TableColumn(field="values1", title="Cluster"),
    TableColumn(field="values2", title="Interaction"),
]



data_table_worst_cases = DataTable(source=source, columns=columns, height=280,
                                   row_headers=False, fit_columns=True)


source.callback = CustomJS(args=dict(source=source), code="""
    console.log( cb_obj.get('data'));
""")

When I click in the table I always get the content of the complete table, not the particular cell.

like image 543
Zoran Milosavljevic Avatar asked Dec 10 '22 13:12

Zoran Milosavljevic


1 Answers

This version uses Python callback (updated for Bokeh v1.0.4). Run as: bokeh serve --show app.py

from random import randint
from datetime import date
from bokeh.models import ColumnDataSource, TableColumn, DateFormatter, DataTable
from bokeh.layouts import column
from bokeh.models.widgets import TextInput
from bokeh.plotting import curdoc

data = dict(dates = [date(2014, 3, i + 1) for i in range(10)],
            downloads = [randint(0, 100) for i in range(10)],
            identities = ['id_' + str(x) for x in range(10)])

source = ColumnDataSource(data)

columns = [TableColumn(field = "dates", title = "Date",
           formatter = DateFormatter()),
           TableColumn(field = "downloads", title = "Downloads")]

data_table = DataTable(source = source, columns = columns, width = 280, height = 280, editable = True)
table_row = TextInput(value = '', title = "Row index:")
table_cell_column_1 = TextInput(value = '', title = "Date:")
table_cell_column_2 = TextInput(value = '', title = "Downloads:")

def function_source(attr, old, new):
    try:
        selected_index = source.selected.indices[0]
        table_row.value = str(selected_index)
        table_cell_column_1.value = str(source.data["dates"][selected_index])
        table_cell_column_2.value = str(source.data["downloads"][selected_index])
    except IndexError:
        pass

source.selected.on_change('indices', function_source)
curdoc().add_root(column(data_table, table_row, table_cell_column_1, table_cell_column_2))

Result:

enter image description here

like image 69
Tony Avatar answered Dec 13 '22 22:12

Tony