我想创建一个交互式python Bokeh图。我有两个数据框,它们由列名链接。
当我在plot1中选择一个条时,我想在图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))
答案 0 :(得分:4)
您缺少一个基本概念。 Bokeh实际上是两个库,Python Bokeh API,以及在浏览器中完成所有工作的JavaScript BokehJS库。这些作品可以通过两种方式进行互动:
独立文件
这些是没有Bokeh服务器支持的Bokeh文档。它们可能有许多工具和交互(例如来自CustomJS回调)但是单向行程,生成自包含的HTML,JavaScript和CSS,它们与任何Python运行时没有进一步的连接。
散景应用
这些是由Bokeh服务器支持的Bokeh文档,并自动同步Python和JS状态。除了独立文档的所有功能外,还可以将事件和工具连接到真正的Python回调,以执行在Bokeh服务器中执行的操作。
如上所述,当您使用output_file
,output_notebook
和show
时,您将创建一个独立 Bokeh文档。这意味着一旦文档显示在浏览器中,根本就没有任何连接到任何Python 。特别是,这意味着您无法访问Pandas Dataframes或NumPy数组或在任何回调中使用Python代码,因为浏览器根本不了解这些内容或Python内容。您只能使用文档的JavaScript Callbacks部分中所述的CustomJS
回调。
如果您需要运行真正的Python代码以响应Bokeh服务器可以提供的事件,选择,工具等。请参阅文档中的Running a Bokeh Server。
根据您的数据大小,您可以使用 Standlone 文档完成所需内容,方法是预先发送Bokeh数据源中的所有数据,并使用{{1}在它之间切换的回调。
答案 1 :(得分:3)
最终@bigreddot帮助我找到了这个Bokeh Server callback from tools。下面代码对我有用:
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))
答案 2 :(得分:1)
这是独立文档的JS回调版本(已在Bokeh 1.0.4上测试):
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;
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)
结果: