Bokeh: DataTable - how to set selected rows

十年热恋 提交于 2019-12-04 02:28:50

See an example app (needs bokeh serve to run) where pressing the button changes the selected rows, then updates both a table and plot. Is this all the functionality you need?

By the way you could just do it in JS and not need to use bokeh server, but if you have more python functionality going on then i guess you need it.

from datetime import date
from random import randint

from bokeh.io import output_file, show, curdoc
from bokeh.plotting import figure
from bokeh.layouts import widgetbox, row
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn,Button

output_file("data_table.html")

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

def update():
    #set inds to be selected
    inds = [1,2,3,4]
    source.selected = {'0d': {'glyph': None, 'indices': []},
                                '1d': {'indices': inds}, '2d': {}}
    # set plot data
    plot_dates = [data['dates'][i] for i in inds]
    plot_downloads = [data['downloads'][i] for i in inds]
    plot_source.data['dates'] = plot_dates
    plot_source.data['downloads'] = plot_downloads


source = ColumnDataSource(data)
plot_source = ColumnDataSource({'dates':[],'downloads':[]})


table_button = Button(label="Press to set", button_type="success")
table_button.on_click(update)
columns = [
        TableColumn(field="dates", title="Date", formatter=DateFormatter()),
        TableColumn(field="downloads", title="Downloads"),
    ]
data_table = DataTable(source=source, columns=columns, width=400, height=280)

p = figure(plot_width=400, plot_height=400)

# add a circle renderer with a size, color, and alpha
p.circle('dates','downloads',source=plot_source, size=20, color="navy", alpha=0.5)


curdoc().add_root(row([table_button,data_table,p]))

Just for clarity you have to replace the source.selected property completely to trigger the changes. So the important line is:

source.selected = {'0d': {'glyph': None, 'indices': []},
                            '1d': {'indices': inds}, '2d': {}}

Individually setting the items in source.selected doesn't work

source.selected['1d']['indices'] = inds # Doesn't work

You can select DataTable rows programmatically in python in this way:

source.selected.indices = [list of indices to be selected]

where source is the ColumnDataSource for the DataTable. If you have any callbacks for the source.selected here, remember to select the rows only after registering the callbacks so that they will get called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!