我注意到,当尝试更新部分 Bokeh 布局时,DataTable 显示发生了变化(见附图),即使没有在代码中明确地对表格进行修改。目标是仅更新散景文档的图表/表格之一,而不修改其余部分。
我通过向根添加一个列对象,然后直接修改列对象的子对象来实现。还有另一种更标准的方法吗?我不知道这是一个错误,还是我通过使用 hack 来更新图表来打破它。
使用的bokeh版本是3.1.0,我用的之前的版本(2.4.2)没有出现这个问题
这是一个说明这种行为的代码:
import bokeh
import bokeh.plotting
import pandas as pd
class BokehPlot:
@staticmethod
def _get_plot(plot_data):
plot_source = bokeh.models.ColumnDataSource(plot_data)
plot = bokeh.plotting.figure(width=800, height=400, x_range=(0, 5), y_range=(0, 20))
plot.line('x', 'y', source=plot_source)
return plot
def draw_plot(self):
table_data = pd.DataFrame(data={'column_1': [11, 21], 'column_2': [12, 22]})
table_source = bokeh.models.ColumnDataSource(data=table_data)
# I tried to specify width and formatter for TableColumn and DataTable as well, but
# that did not change the behaviour
table_columns = [bokeh.models.TableColumn(field=column, title=column) for column in table_data.columns]
table = bokeh.models.DataTable(source=table_source, columns=table_columns)
button = bokeh.models.Button(label='Click')
def update_plot():
plot_data = pd.DataFrame(data={'x': [1, 2], 'y': [12, 8]})
plot = self._get_plot(plot_data)
# Only the second object is replaced, the Button and the DataTable are left as they are
self._layout.children[1] = plot
plot_data = pd.DataFrame(data={'x': [1, 2], 'y': [10, 15]})
plot = self._get_plot(plot_data)
button.on_click(update_plot)
self._layout = bokeh.layouts.column([button, plot, table])
bokeh.io.curdoc().add_root(self._layout)
bokeh_plot = BokehPlot()
bokeh_plot.draw_plot()