Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bokeh update vbar data source

I'm building an histogram plot with running a bokeh server to dynamically change data for an histogram plot. Datasource should change by clicking on button - but it's not working as expected.

from bokeh.plotting import figure
from bokeh.layouts import layout, widgetbox
from bokeh.io import curdoc
from bokeh.transform import factor_cmap
from bokeh.palettes import Spectral6
from bokeh.models import FactorRange, ColumnDataSource
from bokeh.models.widgets import Button

button = Button(label="ChangeValue", button_type="success")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
val = [5, 3, 4, 2, 4, 6]
data_dict = {'x':fruits,'y':val} 
source_table_hist = ColumnDataSource(data=data_dict)

h = figure(x_range=data_dict['x'],plot_height=350, title="Histogram")
h.vbar(x='x', top='y', width=0.2, source=source_table_hist, legend="x", line_color='black', 
       fill_color=factor_cmap('x', palette=Spectral6, factors=data_dict['x']))

h.xgrid.grid_line_color = None
h.y_range.start = 0

inputs = widgetbox(button)

def update():
    fruits = ['Banana', 'Orange']
    val = [15, 23]
    data_dict = {'x':fruits,'y':val}
    h.x_range=FactorRange(factors=data_dict['x']) 
    source_table_hist.data = data_dict

button.on_click(update)
l = layout([inputs,h])
curdoc().add_root(l)
curdoc().title = "Test"
like image 563
MikeLo Avatar asked Feb 07 '26 02:02

MikeLo


1 Answers

The use-case that Bokeh creators had in mind, and the use case that is therefore currently best-supported, is to set up an app, then update the data and properties in place (i.e. as opposed to replacing whole objects like ranges). Your code works for me if this line

h.x_range=FactorRange(factors=data_dict['x'])  # replace entire range (bad) 

is changed to this instead:

h.x_range.factors=data_dict['x']  # update existing range (good)

The new bars are rendered as grey, since the color mapper you configure does not know anything about the new factors you changed to. Some options:

  • configure the color mapper up front for all possible factors that will ever be set

  • update the properties of the color mapper to adjust for the new factors

  • do a color mapping in Python (and put a "color" column in the CDS) instead of using LinearColormapper

like image 96
bigreddot Avatar answered Feb 09 '26 08:02

bigreddot