【问题标题】:Bokeh: How to manually update a figure during callback?散景:如何在回调期间手动更新图形?
【发布时间】:2021-03-19 14:04:09
【问题描述】:

我有一个使用 Bokeh 的应用程序。在回调期间,我更新源以便在图上显示我的数据的另一个特征。到目前为止这工作正常,但实际更新是在回调完成后完成的。 (这在某种程度上是有道理的)。
我的问题是,我可以在回调期间手动更新图形,以获得新的属性,例如更新数据产生的新 y 范围吗?
下面是一个最小的工作示例,应该可以解释我的需求。

import pandas as pd

from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource, Button
from bokeh.layouts import layout

plot = figure(plot_width=1000, plot_height=250)

df = pd.DataFrame({"ID":[0, 1, 2, 3, 4, 5, 6, 7], 
                   "Value1":[0, 100, 200, 300, 400, 500, 600, 700], 
                   "Value2":[0, 1, 2, 4,8 , 16, 32, 64]})
source = ColumnDataSource(df)

plot_data = 'Value1'
source.data['plot_data'] = source.data[plot_data]

line1 = plot.line(x='ID', y='plot_data', source=source)

def function_to_do_stuff_based_on_y_axis_range():
    print(f"After changing source: Y-Axis start: {plot.y_range.start}")
    print(f"After changing source: Y-Axis end: {plot.y_range.end}")

def callback(event):
    global plot_data
    print("Entering Callback...")

    # Change plot_data
    if plot_data == "Value1":
        plot_data = "Value2"
    else:
        plot_data = "Value1"

    print(f"Before changing source: Y-Axis start: {plot.y_range.start}")
    print(f"Before changing source: Y-Axis end: {plot.y_range.end}")

    # actual change of data
    source.data['plot_data'] = source.data[plot_data]
   
    # Here something is needed like 
    # plot.draw_new_and_update_all_attributes() 
    # so that the following fuction has the 'new' attributes of plot.y_range...

    function_to_do_stuff_based_on_y_axis_range()

button_val = Button(label="Toggle Data")
button_val.on_click(callback)

layout_ = layout([[plot],[button_val],])
curdoc().add_root(layout_)

问题是,plot.y_range 仅在我的回调之后更新,如以下输出所示:

输出:

Entering Callback...
Before changing source: Y-Axis start: -35.00000000000006
Before changing source: Y-Axis end: 735
After changing source: Y-Axis start: -35.00000000000006
After changing source: Y-Axis end: 735
Entering Callback...
Before changing source: Y-Axis start: -3.200000000000003
Before changing source: Y-Axis end: 67.2
After changing source: Y-Axis start: -3.200000000000003
After changing source: Y-Axis end: 67.2

对此有何建议?

【问题讨论】:

    标签: python bokeh


    【解决方案1】:

    恐怕只有在回调完成执行后才刷新图表。 如果您希望图表反映步骤的变化,那么您将需要多个回调函数。

    另外,我认为您必须执行source.change.emit() 才能将数据更改保存在回调中。

    https://docs.bokeh.org/en/latest/docs/user_guide/interaction/callbacks.html?highlight=callback

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-24
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多