我正在构建一个直方图,运行一个 Bokeh 服务器以动态更改直方图的数据。数据源应通过单击按钮更改 - 但它没有按预期工作。
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"
最佳答案
Bokeh 创作者想到的用例,也是目前最受支持的用例,是设置一个应用程序,然后更新到位的数据和属性(即而不是替换像范围这样的整个对象)。如果这一行,你的代码对我有用
h.x_range=FactorRange(factors=data_dict['x']) # replace entire range (bad)
改为:
h.x_range.factors=data_dict['x'] # update existing range (good)
新条形图呈现为灰色,因为您配置的颜色映射器对您更改的新因素一无所知。一些选项:
为所有可能设置的因素预先配置颜色映射器
更新颜色映射器的属性以针对新因素进行调整
在 Python 中进行颜色映射(并在 CDS 中放置一个“颜色”列)而不是使用
LinearColormapper
关于python - bokeh更新vbar数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488944/