首页 文章

Bokeh回调不会更新图表

提问于
浏览
1

我目前正试图在共享选择的2个图中绘制数据帧的平均值和最大值 . 在图1的选择中,我想绘制在图2中被平均的数据 . 我正在获得图形和选择,但它似乎没有用spyder中的选择更新图形 . 在我的代码下面 .

import pandas as pd
import numpy as np
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show
from bokeh.layouts import row
from bokeh.io import curdoc

# data for plot 2
df2 = pd.DataFrame(list([[1,1,2,3],[3,4,4,5]]))

source2 = ColumnDataSource(
        data=dict(
            x=list(df2.index.values),
            y=list(df2.iloc[:,0].values)
        )
    )

# data for plot 1 & 0
df1 = np.mean(df2)
df0 = np.max(df2)
source1 = ColumnDataSource(
        data=dict(
            x=list(range(0,df1.shape[0])),
            y=list(df1.values),
            y1=list(df0.values),
                    )
    )

# Plot graph one with data from df1 and source 1 as barplot
plot1 = figure(plot_height=300, plot_width=400, tools="box_select")
barglyph = plot1.circle(x='x',y='y',source=source1)

# Plot graph one with data from df1 and source 1 as barplot
plot0 = figure(plot_height=300, plot_width=400, tools="box_select")
barglyph = plot0.circle(x='x',y='y1',source=source1)



# Plot graph two with data from df2 and source 2 as line
plot2 = figure(plot_height=300, plot_width=400, title="myvalues", 
              tools="box_zoom,reset,save,wheel_zoom,hover")    
r1 = plot2.line(x='x',y='y',source =source2, line_alpha = 1, line_width=1)
# safe data from plot 2 for later change in subroutine
ds1 = r1.data_source

def callback(attr, old, new):
    patch_name =  source1.data['colnames'][new['1d']['indices'][0]]
    ds1.data['y'] = df2[patch_name].values

barglyph.data_source.on_change('selected',callback)
show(row(plot0,plot1,plot2))
curdoc().add_root(row(plot0,plot1,plot2))

如果我在jupyter中运行它我得到错误:AttributeError:'Document'对象没有属性'references'

1 回答

  • 1

    使用真正的Python回调,例如使用 on_change 要求在Bokeh服务器中将代码作为Bokeh server application运行 . 浏览器无法运行运行Python代码的能力 . 如果您只是将代码作为"regular" Python脚本 python app.py 运行,那么Python运行代码,在浏览器中生成输出,然后Python解释器退出 - 此时没有Python进程来运行您的回调代码 . 因此,Bokeh服务器是持久的,长期运行的Python进程,用于在Bokeh应用程序中运行真正的Python回调 .

    有几种方法可以运行Bokeh服务器应用程序:

    • 作为一个单独的过程 . 通常,如果您的应用程序代码位于 app.py 中,则表示执行类似于以下命令行命令:
    bokeh serve --show app.py
    

    这将在本地浏览器中打开应用程序的会话 .

    • 嵌入在Jupyter笔记本中 . 在这种情况下,您可以在 myapp(doc) 之类的函数中定义应用程序代码,该函数接受Bokeh Document 并将所有您想要的内容(绘图,小部件,工具,回调等)添加到该文档中 . 然后在笔记本中执行:
    show(myapp)
    

    并且应用程序将在笔记本中显示并内联运行 . 您可以在本地下载并运行此complete example notebook以获取更多详细信息 .

    否则,如果您想要运行Bokeh服务器,则可以使用Javascript Callbacks实现许多交互式功能,这些功能在独立(非服务器)Bokeh文档中运行 .

相关问题