I have a bokeh table that is linked to a plot, and is working as intended. Selecting a row in the table mutes all the non-selected rows in the plot display.
However, what if someone wants to select a column, and hide all other columns in the plot? Is this possible using a bokeh widget? Or does some custom code need to be written for this feature? I have attached to code used to produce the widget table on the bokeh website, as it is the most simple example I can think of (and quickest).
from datetime import date
from random import randint
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
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)],
)
source = ColumnDataSource(data)
columns = [
TableColumn(field="dates", title="Date", formatter=DateFormatter()),
TableColumn(field="downloads", title="Downloads"),
]
data_table = DataTable(source=source, columns=columns, width=400, height=280)
show(widgetbox(data_table))
Here is a code with a JS callback that allows you to know the selected row and column.
from bokeh.io import show
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import DataTable,TableColumn
column_list = ['col1','col2','col3']
source = ColumnDataSource(data = {key:range(10) for key in column_list})
columns = [TableColumn(field=col, title=col) for col in column_list]
data_table = DataTable(source=source, columns=columns, width=400, height=280,selectable=True)
source_code = """
var grid = document.getElementsByClassName('grid-canvas')[0].children;
var row = '';
var col = '';
for (var i=0,max=grid.length;i<max;i++){
if (grid[i].outerHTML.includes('active')){
row=i;
for (var j=0,jmax=grid[i].children.length;j<jmax;j++){
if(grid[i].children[j].outerHTML.includes('active')){col=j}
}
}
}
console.log('row',row);
console.log('col',col);
cb_obj.selected['1d'].indices = [];
"""
source.callback = CustomJS(code= source_code)
show(widgetbox(data_table))
The line cb_obj.selected['1d'].indices = []; just resets the selected indices so that the callback can trigger even if the same cell is clicked multiple times
You can then do what you want with the row/column index
If you need to you can also "transfer" the values back to python by updating a ColumnDatasource with the row and column values.
I use bokeh 0.12.10 so this may require some change with the latest version
EDIT: tested with 0.12.16 and it still works
EDIT: update for bokeh 1.1.0
from bokeh.io import show
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import DataTable,TableColumn
column_list = ['col1','col2','col3']
source = ColumnDataSource(data = {key:range(20) for key in column_list})
columns = [TableColumn(field=col, title=col) for col in column_list]
data_table = DataTable(source=source, columns=columns, width=400, height=280,selectable=True)
source_code = """
var grid = document.getElementsByClassName('grid-canvas')[0];
var active_row = grid.querySelectorAll('.active')[0];
if (active_row!=undefined){
var active_row_ID = Number(active_row.children[0].innerText);
for (var i=1, imax=active_row.children.length; i<imax; i++){
if (active_row.children[i].className.includes('active')){
var active_col_ID = i-1;
}
}
console.log('row',active_row_ID);
console.log('col',active_col_ID);
var active_cells = grid.querySelectorAll('.active');
for (i=0, imax=active_cells.length;i<imax;i++){
active_cells[i].classList.remove('active');
}
cb_obj.indices = [];
}
"""
source.selected.js_on_change('indices', CustomJS(args={'source':source},code= source_code) )
show(widgetbox(data_table))
As of Bokeh 0.12.16 the built-in DataTable does not support any sort of column selection or click events. Looking at the descriptions of Grid Events for the underlying SlickGrid implementation, it appears that onClick and onHeaderClick are supported at the low level. So the immediately accessible option would be Extending Bokeh with a custom DataTable subclass. Otherwise you can submit a GitHub feature request issue to discuss exposing these events somehow in the built in table.
Related
I am trying to pass .opts() arguments to style a holoviews .Bars graph, but all arguments are being ignored when passed. This results in the following error:
WARNING:param.Bars02978: Use of call to set options will be deprecated in the next major release (1.14.0). Use the equivalent .opts method instead.
I am on version 1.14.8.
How can I pass the .opts() so my graph can be styled appropriately?
# https://www.youtube.com/watch?v=ZWP_h6WV8h0 Connecting multiple plots
from collections import defaultdict
import panel as pn
import holoviews as hv
from holoviews import opts
import pandas as pd
import numpy as np
import pandas_bokeh
import bokeh
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, TableColumn, DataTable, DateEditor, IntEditor\
, DateFormatter, NumeralTickFormatter, CustomJS, DatePicker, widgets
from bokeh.models import Panel, Tabs, Row
from bokeh.io import show
from bokeh.layouts import Column, layout
import hvplot.pandas
hv.extension('bokeh', 'matplotlib')
renderer = hv.renderer('bokeh')
renderer = renderer.instance(mode='server')
data = {
"calories": [420],
"duration": [50],
"ggg": [60]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df)
df2 = pd.DataFrame({'Missing Data': df[['calories']].sum(axis=1), 'Delayed Data': df[['duration']].sum(axis=1)
, 'Duplicate Data': df[['ggg']].sum(axis=1)})
print(df2)
bar_opts = opts.Bars(height=400, width=600, tools=["hover"], bgcolor="grey", xlabel="Wine Class", ylabel="Malic Acid", ylim=(0.0, 3.5))
bars = hv.Bars(pd.melt(df2.reset_index(), ['index']), ['index', 'variable'], 'value', label='dl_refined_analytics').opts(bar_opts)
bars.opts(height=400, width=600, tools=["hover"], bgcolor="grey", xlabel="Wine Class", ylabel="Malic Acid", ylim=(0.0, 3.5))
dmap = hv.DynamicMap(bars)
app = pn.Row(dmap)
app.show() ```
What was the intent behind hv.DynamicMap(bars)? I'm not sure why you'd want to pass the bars object to a DynamicMap constructor, and if you just use app = pn.Row(bars) instead of app = pn.Row(dmap) it should work fine.
I am using Bokeh DataTable to present an editable table and I wish to color the text in the cell if the value has changed by the user.
I was trying to use HTMLTemplateFormatter but I am not sure what to do.
If a user changed the value of row #2 I wish the text to be colored like that:
an example based on How to color rows and/or cells in a Bokeh DataTable?:
from bokeh.plotting import curdoc
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, TableColumn, HTMLTemplateFormatter
orig_data = dict(
cola=[1, 2, 3, 4, 5, 6],
)
data = orig_data
source = ColumnDataSource(data)
template = """
<div style="color: <%=
(function colorfromint(){
if(orig_data.cola != data.cola){return('red')} // I don't know what to write here
}()) %>;">
<%= value %>
</font>
</div>
"""
formatter = HTMLTemplateFormatter(template=template)
columns = [TableColumn(field="cola", title="CL1", formatter=formatter, width=100)]
data_table = DataTable(source=source,
columns=columns,
editable=True,
width=100)
curdoc().add_root(data_table)
Can I compare different tables using the HTMLTemplateFormatter block?
if not, from the HTMLTemplateFormatter Bokeh documentation:
"The formatter has access other items in the row via the dataContext object passed to the formatted"
So one solution I can think of is joining the tables and make the compare with the dataContext object, presenting only the columns I select
But, I'm not sure how to it and it seems to me like a "dirty" workaround
I'm quite familiar with python but I'm new with Bokeh.
Is there a good and easy way to do it?
maybe other methods other than HTMLTemplateFormatter?
Since default Bokeh formatters work on whole columns, you will have to create your own formatter.
The example below works even without Bokeh server, that's why it uses show. But you can replace it with curdoc().add_root - it should work just the same.
from bokeh.core.property.container import List
from bokeh.core.property.primitive import Int
from bokeh.io import show
from bokeh.models import ColumnDataSource, CustomJS, StringFormatter
from bokeh.models.widgets import DataTable, TableColumn
data = dict(cola=[1, 2, 3, 4, 5, 6],
colb=[1, 2, 3, 4, 5, 6])
orig_ds = ColumnDataSource(data)
ds = ColumnDataSource(copy.deepcopy(data))
class RowIndexFormatter(StringFormatter):
rows = List(Int, default=[])
# language=TypeScript
__implementation__ = """\
import {StringFormatter} from "models/widgets/tables/cell_formatters"
import * as p from "core/properties"
import {div} from "core/dom"
export namespace RowIndexFormatter {
export type Attrs = p.AttrsOf<Props>
export type Props = StringFormatter.Props & {
rows: p.Property<number[]>
}
}
export interface RowIndexFormatter extends RowIndexFormatter.Attrs {}
export class RowIndexFormatter extends StringFormatter {
properties: RowIndexFormatter.Props
constructor(attrs?: Partial<RowIndexFormatter.Attrs>) {
super(attrs)
}
static init_RowIndexFormatter(): void {
this.define<RowIndexFormatter.Props>({
rows: [ p.Array, [] ]
})
}
doFormat(row: any, _cell: any, value: any, _columnDef: any, _dataContext: any): string {
// Mostly copied from `StringFormatter`, except for taking `rows` into account.
const {font_style, text_align, text_color} = this
const text = div({}, value == null ? "" : `${value}`)
switch (font_style) {
case "bold":
text.style.fontWeight = "bold"
break
case "italic":
text.style.fontStyle = "italic"
break
}
if (text_align != null)
text.style.textAlign = text_align
if (text_color != null && this.rows.includes(row))
text.style.color = text_color
return text.outerHTML
}
}
"""
columns = [TableColumn(field="cola", title="CL1", formatter=RowIndexFormatter(text_color='red')),
TableColumn(field="colb", title="CL2", formatter=RowIndexFormatter(text_color='blue'))]
table = DataTable(source=ds, columns=columns, editable=True)
cb = CustomJS(args=dict(orig_ds=orig_ds, table=table),
code="""\
const columns = new Map(table.columns.map(c => [c.field, c]));
for (const c of cb_obj.columns()) {
const orig_col = orig_ds.data[c];
const formatter = columns.get(c).formatter;
formatter.rows = [];
cb_obj.data[c].forEach((val, idx) => {
if (val != orig_col[idx]) {
formatter.rows.push(idx);
}
});
}
table.change.emit();
""")
ds.js_on_change('data', cb)
ds.js_on_change('patching', cb)
show(table)
In the example below, I am trying to get the x and y coordinates that appear in the Div next to the plot when the bokeh plot is Tapped to be appended to the data dictionary coordList in their respective list.
import numpy as np
from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import CustomJS, Div
from bokeh.layouts import column, row
from bokeh.events import Tap
coordList = dict(x=[], y=[])
output_notebook()
def display_event(div, attributes=[], style = 'float:left;clear:left;font_size=10pt'):
"Build a suitable CustomJS to display the current event in the div model."
return CustomJS(args=dict(div=div), code="""
var attrs = %s; var args = [];
for (var i = 0; i<attrs.length; i++) {
args.push(Number(cb_obj[attrs[i]]).toFixed(2));
}
var line = "<span style=%r>(" + args.join(", ") + ")</span>\\n";
var text = div.text.concat(line);
var lines = text.split("\\n")
if (lines.length > 35)
lines.shift();
div.text = lines.join("\\n");
""" % (attributes, style))
x = np.random.random(size=4000) * 100
y = np.random.random(size=4000) * 100
radii = np.random.random(size=4000) * 1.5
colors = ["#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)]
p = figure(tools="pan,wheel_zoom,zoom_in,zoom_out,reset")
p.scatter(x, y, radius=np.random.random(size=4000) * 1.5,
fill_color=colors, fill_alpha=0.6, line_color=None)
div = Div(width=400, height=p.plot_height)
layout = row(p, div)
point_attributes = ['x', 'y']
p.js_on_event(Tap, display_event(div, attributes=point_attributes))
show(layout)
I'm not sure how the coordinates are saved and how to access them and append them to the lists.
There is no way to append to coordinates to a python object with code like above, because that code is generating standalone output (i.e. it is using "show"). Standalone output is pure static HTML and Bokeh JSON that is sent to browser, without any sort of connection to any Python process. If you want to connect Bokeh visualizations to a real running Python process, that is what the Bokeh server is for.
If you run a Bokeh server application, then you can use on_event with a real python callback to run whatever python code you want with the Tap even values:
def callback(event):
# use event['x'], event['y'], event['sx'], event['sy']
p.on_event(Tap, callback)
The below code is a minimal example of an issues where a bokeh model doesn't update when it's attribute is set via a callback. I've found that removing and adding back a model object (not even the suspect one) from the layout of the curdoc forces it to refresh. I've shown this via the first button press.
Is there a more elegant way to force bokeh to redraw the figure?
The example is for DataTable.columns.formatter, but I've noticed that this applies to other model attributes as well (including axis ranges, where I've seen a workaround involving setting the range explicitly at figure creation to allow updates).
from bokeh.models.widgets import Dropdown, RadioButtonGroup, CheckboxGroup, \
Toggle, DataTable, TableColumn, NumberFormatter
from bokeh.plotting import figure, curdoc, ColumnDataSource
from bokeh.layouts import column, layout
def update_format(attr, old, new):
if toggle_commas.active == 1:
(t.columns[1].formatter)
# remove the commas
t.columns[1].formatter = NumberFormatter(format='0,0.[00]')
# show that it updates the actual attribute
print(t.columns[1].formatter)
del doc_layout.children[-1]
doc_layout.children.insert(1, toggle_commas)
else:
# change the formatter back and note that it doesn't update the table unless you remove and add something
(t.columns[1].formatter)
# remove the commas
t.columns[1].formatter = NumberFormatter(format='0.[00]')
# show that it updates the actual attribute
print(t.columns[1].formatter)
table_data = dict(
percentiles=['min', '1st', '5th', '10th', '25th', '50th',
'75th', '90th', '95th', '99th', 'max', '', 'mean', 'std'],
values=[i for i in range(1000, 1014)]
)
table_source = ColumnDataSource(table_data)
table_columns = [
TableColumn(field="percentiles", title="Percentile"),
TableColumn(field="values", title="Value", formatter=NumberFormatter(format='0.[00]'))
]
t = DataTable(source=table_source, columns=table_columns, width=400, height=600,
name='pct_table')
toggle_commas = Toggle(label='Commas', active=False)
toggle_commas.on_change('active', update_format)
doc_layout = layout(t, toggle_commas)
curdoc().add_root(doc_layout)
I am experimenting with bokeh data table to display data embedded in web page. It works quite nicely.
Is there a way to save the table content from the displayed data table? Other bokeh plots have tool bar for various functions including saving, but the DataTable does not seem to come with it. I know very little about javascript or slickgrid, which bokeh data table uses. And wondering if it can be done.
Thanks!
EDIT - It appears the my original question was not clear enough. Hope following pictures can help to illustrate:
Bokeh plot has toolbars associated:
But data table does not have it by default, and it won't take 'tools' parameter either:
Is it possible to add 'save' button to data table so the person view the table can download as tab delimited or csv files? Not necessarily need to be look the same, but with the same function for saving.
2021 Update: adjusted code that works in python 3.8 and bokeh 2.2.3
For those who have trouble adjusting or finding the example on the bokeh website or are just very lazy, the below code does the minimal job:
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import Button
from bokeh.io import show
import os
source = ColumnDataSource({'list1':[0,1,2,3],'list2':[4,5,6,7]})
button = Button(label="Download", button_type="success")
button.js_on_click(CustomJS(args=dict(source=source),code=open(os.path.join(os.path.dirname(__file__),"download.js")).read()))
show(button)
And the file download.js:
function table_to_csv(source) {
const columns = Object.keys(source.data)
const nrows = source.get_length()
const lines = [columns.join(',')]
for (let i = 0; i < nrows; i++) {
let row = [];
for (let j = 0; j < columns.length; j++) {
const column = columns[j]
row.push(source.data[column][i].toString())
}
lines.push(row.join(','))
}
return lines.join('\n').concat('\n')
}
const filename = 'data_result.csv'
const filetext = table_to_csv(source)
const blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' })
//addresses IE
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename)
} else {
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = filename
link.target = '_blank'
link.style.visibility = 'hidden'
link.dispatchEvent(new MouseEvent('click'))
}
It would be nice if bokeh provides a tool button for saving/exporting the data table to csv / txt / excel files. If it already does, I have not found it in the document yet.
In the mean time, a possible answer is to export the js array (that is underneath the bokeh data table) to CSV using native javascript. It has been described here and here.
ADD: bokeh has callbacks for using js. A simple description is here. still reading about it ...
EDIT: It is probably there for a while now, but I have just noticed an example on Bokeh website for saving csv from data table.
Related to my response to this stackoverflow question. Response copied below:
Here is a working example with Python 3.7.5 and Bokeh 1.4.0
public github link to this jupyter notebook:
https://github.com/surfaceowl-ai/python_visualizations/blob/master/notebooks/bokeh_save_linked_plot_data.ipynb
environment report:
virtual env python version: Python 3.7.5
virtual env ipython version: 7.9.0
watermark package reports:
bokeh 1.4.0
jupyter 1.0.0
numpy 1.17.4
pandas 0.25.3
rise 5.6.0
watermark 2.0.2
# Generate linked plots + TABLE displaying data + save button to export cvs of selected data
from random import random
from bokeh.io import output_notebook # prevent opening separate tab with graph
from bokeh.io import show
from bokeh.layouts import row
from bokeh.layouts import grid
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.models import Button # for saving data
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
from bokeh.models import HoverTool
from bokeh.plotting import figure
# create data
x = [random() for x in range(500)]
y = [random() for y in range(500)]
# create first subplot
plot_width = 400
plot_height = 400
s1 = ColumnDataSource(data=dict(x=x, y=y))
fig01 = figure(
plot_width=plot_width,
plot_height=plot_height,
tools=["lasso_select", "reset", "save"],
title="Select Here",
)
fig01.circle("x", "y", source=s1, alpha=0.6)
# create second subplot
s2 = ColumnDataSource(data=dict(x=[], y=[]))
# demo smart error msg: `box_zoom`, vs `BoxZoomTool`
fig02 = figure(
plot_width=400,
plot_height=400,
x_range=(0, 1),
y_range=(0, 1),
tools=["box_zoom", "wheel_zoom", "reset", "save"],
title="Watch Here",
)
fig02.circle("x", "y", source=s2, alpha=0.6, color="firebrick")
# create dynamic table of selected points
columns = [
TableColumn(field="x", title="X axis"),
TableColumn(field="y", title="Y axis"),
]
table = DataTable(
source=s2,
columns=columns,
width=400,
height=600,
sortable=True,
selectable=True,
editable=True,
)
# fancy javascript to link subplots
# js pushes selected points into ColumnDataSource of 2nd plot
# inspiration for this from a few sources:
# credit: https://stackoverflow.com/users/1097752/iolsmit via: https://stackoverflow.com/questions/48982260/bokeh-lasso-select-to-table-update
# credit: https://stackoverflow.com/users/8412027/joris via: https://stackoverflow.com/questions/34164587/get-selected-data-contained-within-box-select-tool-in-bokeh
s1.selected.js_on_change(
"indices",
CustomJS(
args=dict(s1=s1, s2=s2, table=table),
code="""
var inds = cb_obj.indices;
var d1 = s1.data;
var d2 = s2.data;
d2['x'] = []
d2['y'] = []
for (var i = 0; i < inds.length; i++) {
d2['x'].push(d1['x'][inds[i]])
d2['y'].push(d1['y'][inds[i]])
}
s2.change.emit();
table.change.emit();
var inds = source_data.selected.indices;
var data = source_data.data;
var out = "x, y\\n";
for (i = 0; i < inds.length; i++) {
out += data['x'][inds[i]] + "," + data['y'][inds[i]] + "\\n";
}
var file = new Blob([out], {type: 'text/plain'});
""",
),
)
# create save button - saves selected datapoints to text file onbutton
# inspriation for this code:
# credit: https://stackoverflow.com/questions/31824124/is-there-a-way-to-save-bokeh-data-table-content
# note: savebutton line `var out = "x, y\\n";` defines the header of the exported file, helpful to have a header for downstream processing
savebutton = Button(label="Save", button_type="success")
savebutton.callback = CustomJS(
args=dict(source_data=s1),
code="""
var inds = source_data.selected.indices;
var data = source_data.data;
var out = "x, y\\n";
for (i = 0; i < inds.length; i++) {
out += data['x'][inds[i]] + "," + data['y'][inds[i]] + "\\n";
}
var file = new Blob([out], {type: 'text/plain'});
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(file);
elem.download = 'selected-data.txt';
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
""",
)
# add Hover tool
# define what is displayed in the tooltip
tooltips = [
("X:", "#x"),
("Y:", "#y"),
("static text", "static text"),
]
fig02.add_tools(HoverTool(tooltips=tooltips))
# display results
# demo linked plots
# demo zooms and reset
# demo hover tool
# demo table
# demo save selected results to file
layout = grid([fig01, fig02, table, savebutton], ncols=3)
output_notebook()
show(layout)
# things to try:
# select random shape of blue dots with lasso tool in 'Select Here' graph
# only selected points appear as red dots in 'Watch Here' graph -- try zooming, saving that graph separately
# selected points also appear in the table, which is sortable
# click the 'Save' button to export a csv
# TODO: export from Bokeh to pandas dataframe