Eric Valente
Eric Valente

Reputation: 439

Dynamically assign columns to Bokeh datatable

I have a datatable that is driven by a ColumnDataSource().

My column headers are dynamically assigned depending on the data that is selected.

I have a Select() dropdown set up with dropdown.select.on_change() and in the update function I pull the new data and assign using:

table.data = {}

However I want to change the column names during the on_change() call.

I don't see a simple way to accomplish this in the documentation.

Upvotes: 0

Views: 1638

Answers (1)

Tony
Tony

Reputation: 8287

Not officially supported but you can just assign new columns to your table like this (working for Bokeh v1.0.4). Run with bokeh serve --show app.py

from random import random
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource, DataTable, TableColumn, StringEditor, IntEditor, NumberEditor

source = ColumnDataSource(dict(index = [0], NAME = ["bar"], ID = [1], S1 = [2]))

original_columns = [
    TableColumn(field = "NAME", title = "Name", editor = StringEditor(), name = 'custom_header_name'),
    TableColumn(field = "ID", title = "ID", editor = IntEditor()),
    TableColumn(field = "S1", title = "Value", editor = NumberEditor()) ]

modyfied_columns = [
    TableColumn(field = "NAME", title = "Foo", editor = StringEditor(), name = 'custom_header_name'),
    TableColumn(field = "ID", title = "Bar", editor = IntEditor()),
    TableColumn(field = "S1", title = "Oeps", editor = NumberEditor()) ]

data_table = DataTable(source = source, width = 1000, height = 80, columns = original_columns)

data_table.height = 2000
i = 0

def update_data():
    global i, data_table, original_columns

    if i % 2 == 0:
        data_table.columns = modyfied_columns
    else:
        data_table.columns = original_columns

    NAME, ID, S1 = "foo", i, random()
    i += 1

    data = dict(index = [i], NAME = [NAME], ID = [ID], S1 = [S1])
    source.stream(data, 500)

curdoc().add_root(data_table)
curdoc().add_periodic_callback(update_data, 500)

Result;

enter image description here

Upvotes: 2

Related Questions