Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 两个交互式bokeh图:在一个图形中选择一个值,然后更改另一个_Python_Bokeh_Interactive - Fatal编程技术网

Python 两个交互式bokeh图:在一个图形中选择一个值,然后更改另一个

Python 两个交互式bokeh图:在一个图形中选择一个值,然后更改另一个,python,bokeh,interactive,Python,Bokeh,Interactive,我想创建一个交互式python Bokeh图。我有两个由列名链接的数据帧。 当我在绘图1中选择一个条形图时,我想在绘图2中显示属于该列的数据帧2(df2)的数据。 例如,df1可以包含df2所有列的平均值。如果单击显示的平均值,则可以在第二个图形中显示构成平均值基础的原始数据。 不幸的是,我不能让它工作,我找不到一个可比的例子。以下是我到目前为止的情况。我假设错误在mycolumn=“@colnames”中,并且taptool没有返回我期望的结果。 根据@bigreddot的评论更新了下面的源代

我想创建一个交互式python Bokeh图。我有两个由列名链接的数据帧。 当我在绘图1中选择一个条形图时,我想在绘图2中显示属于该列的数据帧2(df2)的数据。 例如,df1可以包含df2所有列的平均值。如果单击显示的平均值,则可以在第二个图形中显示构成平均值基础的原始数据。 不幸的是,我不能让它工作,我找不到一个可比的例子。以下是我到目前为止的情况。我假设错误在
mycolumn=“@colnames”
中,并且taptool没有返回我期望的结果。 根据@bigreddot的评论更新了下面的源代码

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

# data for plot 2
df2 = pd.DataFrame({"A" : np.linspace(10, 20, 10),
                    "B" : np.linspace(20, 30, 10),
                    "C" : np.linspace(30, 40, 10),
                    "D" : np.linspace(40, 50, 10),
                    "E" : np.linspace(50, 60, 10),})
source2 = ColumnDataSource(
        data=dict(
            x=list(df2.index.values),
            y=list(df2.iloc[:,0].values)
        )
    )

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

# Plot graph one with data from df1 and source 1 as barplot
plot1 = figure(plot_height=300, plot_width=400, tools="tap")
plot1.vbar(x='x',top='y',source=source1, bottom=0,width =0.5)


# Plot graph two with data from df2 and source 2 as line
plot2 = figure(plot_height=300, plot_width=400, title="myvalues", 
              tools="crosshair,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 update_plot2(mycolumn):
    try:
        ds1.data['y'] = df2[mycolumn].values
    except:   
        pass

# add taptool to plot1
taptool = plot1.select(type=TapTool)
taptool.callback = update_plot2(mycolumn="@colnames")

#show(row(plot1,plot2))
curdoc().add_root(row(plot1,plot2))

有一个基本的概念你还没有找到。Bokeh实际上是两个库,Python Bokeh API和JavaScript BokehJS库,它们在浏览器中完成所有工作。这些片段有两种相互作用的方式:

  • 独立文档

    这些是没有Bokeh服务器支持的Bokeh文档。它们可能有许多工具和交互(例如来自CustomJS回调),但都是单向的,生成自包含的HTML、JavaScript和CSS,与任何Python运行时都没有进一步的连接

  • Bokeh应用程序

    这些是由Bokeh服务器支持的Bokeh文档,可以自动同步Python和JS状态。除了独立文档的所有特性外,还可以将事件和工具连接到真正的Python回调,以便在Bokeh服务器中执行

当您如上所述使用
output\u file
output\u notebook
show
时,您正在创建一个独立的Bokeh文档。这意味着,一旦文档显示在浏览器中,就不再与任何Python连接。特别是,这意味着您不能访问诸如Pandas数据帧或NumPy数组之类的内容,也不能在任何回调中使用Python代码,因为浏览器根本不了解这些内容或Python。您只能使用文档部分中描述的
CustomJS
回调

如果您需要运行真正的Python代码来响应事件、选择、工具等,这就是Bokeh服务器可以提供的。请参阅文档中的


根据您的数据大小,通过预先发送Bokeh数据源中的所有数据,并使用一个
CustomJS
回调在它之间进行切换,您可以使用一个独立的文档来完成您想要的任务

最终@bigreddot帮我找到了这个。下面是对我有用的代码:

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


# data for plot 2
df2 = pd.DataFrame({"A" : sample(np.linspace(10, 20, 10),5),
                    "B" : sample(np.linspace(20, 30, 10),5),
                    "C" : sample(np.linspace(30, 40, 10),5),
                    "D" : sample(np.linspace(40, 50, 10),5),
                    "E" : sample(np.linspace(50, 60, 10),5),})
source2 = ColumnDataSource(
        data=dict(
            x=list(df2.index.values),
            y=list(df2.iloc[:,0].values)
        )
    )

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

# Plot graph one with data from df1 and source 1 as barplot
plot1 = figure(plot_height=300, plot_width=400, tools="tap")
barglyph = plot1.vbar(x='x',top='y',source=source1, bottom=0,width =0.5)


# Plot graph two with data from df2 and source 2 as line
plot2 = figure(plot_height=300, plot_width=400, title="myvalues", 
              tools="crosshair,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
    print("TapTool callback executed on Patch {}".format(patch_name))

# add taptool to plot1
barglyph.data_source.on_change('selected',callback)

curdoc().add_root(row(plot1,plot2))

这是一个独立文档的JS回调版本(在Bokeh 1.0.4上测试):

结果:


thx@bigreddot,我修改了上面的示例,使其作为服务器运行,但不幸的是,它仍然没有更新正确的图形。
from bokeh.layouts import row
from bokeh.models import ColumnDataSource, CustomJS, TapTool
from bokeh.plotting import figure, show
import numpy as np

source_bars = ColumnDataSource({'x': [1, 2, 3], 'y': [2, 4, 1] , 'colnames': ['A', 'B', 'C']})
lines_y = [np.random.random(5) for i in range(3)]

plot1 = figure(tools = 'tap')
bars = plot1.vbar(x = 'x', top = 'y', source = source_bars, bottom = 0, width = 0.5)

plot2 = figure()
lines = plot2.line(x = 'x', y = 'y', source = ColumnDataSource({'x': np.arange(5), 'y': lines_y[0]}))
lines.visible = False

code = '''if (cb_data.source.selected.indices.length > 0){
            lines.visible = true;
            var selected_index = cb_data.source.selected.indices[0];
            lines.data_source.data['y'] = lines_y[selected_index]
            lines.data_source.change.emit(); 
          }'''

plots = row(plot1, plot2)
plot1.select(TapTool).callback = CustomJS(args = {'lines': lines, 'lines_y': lines_y}, code = code)
show(plots)