如何动态更改布局?如何正确添加和删除布局对象?

Che*_*uCR 6 python layout plot python-3.x bokeh

我需要构建一个包含许多图的应用程序。它将有一些选项卡,以及带有一些绘图的选项卡内的一个网格图。此外,我需要在服务器运行时动态更新绘图布局。

  • 删除或添加一些图
  • 删除或添加一些标签

我已阅读此线程,其中 Bryan (@bigreddot) 说:

最常用和最容易理解(以及更有效)的方法是预先创建一次绘图,然后在需要更改时仅更新它们的数据。

Bokeh 的布局能力雄心勃勃且复杂。它在许多情况下都能很好地工作,但我可以很容易地相信,在替换复杂的复合模型(如嵌套布局深处的整个图)时,可能会暴露更新错误。

我编写了以下示例,其中以四种不同的方式更新布局:

  1. 用布局对象上的 children 属性替换旧图。
  2. 将布局替换为 curdoc()
  3. 使用remove()和替换绘图append()
  4. 使用插入新图 insert()
from bokeh.models import Button, ColumnDataSource
from bokeh.layouts import column
from bokeh.plotting import curdoc, figure

# ------------------- PLOT 1 --------------------------- #

plot_1 = figure(
    width=400,
    height=400,
)

x = [1, 2, 3, 4]
y = [4, 3, 2, 1]

source = ColumnDataSource(data=dict(x=x, y=y))

plot_1.circle(
    x='x',
    y='y',
    source=source,
    radius=0.5,
    fill_alpha=0.6,
    fill_color='green',
)

# ------------------- PLOT 2 --------------------------- #

plot_2 = figure(
    width=400,
    height=400,
)

plot_2.circle(
    x='x',
    y='y',
    source=source,
    radius=0.5,
    fill_alpha=0.6,
    fill_color='red',
)

# ------------------- PLOT 3 --------------------------- #

plot_3 = figure(
    width=400,
    height=400,
)

plot_3.circle(
    x='x',
    y='y',
    source=source,
    radius=0.5,
    fill_alpha=0.6,
    fill_color='yellow',
)

# ------------------- BUTTONS --------------------------- #

def replace_by_children_attr():
    column_1.children = buttons + [plot_2]

def replace_by_curdoc():
    column_2 = column(buttons + [plot_2])

    curdoc().clear()
    curdoc().add_root(column_2)

def replace_by_remove_append():
    column_1.children.remove(plot_1)
    column_1.children.append(plot_2)

def insert_plot():
    column_1.children.insert(2, plot_3)

button_1 = Button(label="Replace plot by children attribute", button_type="success")
button_1.on_click(replace_by_children_attr)

button_2 = Button(label="Replace plot by curdoc", button_type="success")
button_2.on_click(replace_by_curdoc)

button_3 = Button(label="Replace plot remove-append", button_type="success")
button_3.on_click(replace_by_remove_append)

button_4 = Button(label="Insert plot", button_type="success")
button_4.on_click(insert_plot)

# ------------------- LAYOUT --------------------------- #

buttons = [button_1, button_2, button_3, button_4]
column_1 = column(buttons + [plot_1])

curdoc().add_root(column_1)

I realized that if I press the button "Replace plot by children attribute" the layout changes a little. But when I press "Replace plot by curdoc" the layout is not changed:
Run Code Online (Sandbox Code Playgroud)
  • 那么,这些选项中哪一个是最佳解决方案?
  • 这些解决方案中的任何一个都会给我带来问题吗?我知道至少第一个选项肯定会给我带来问题

注意:实际上,我想避免的是重新启动散景服务器以重建布局,因为它需要一段时间。而且我需要经常这样做。

注 2:散景版本 0.12.14