gpt4 book ai didi

python - Bokeh 服务器 - 如何在回调函数中操作选择

转载 作者:行者123 更新时间:2023-11-28 17:06:43 28 4
gpt4 key购买 nike

我正在绘制几个补丁,这些补丁按数据源中的“组”类别分组。我想要实现的是:通过单击一个补丁,不仅补丁本身而且同一组的所有补丁都应突出显示为选中。

我发现 ColumnDataSource 有一个属性selected。然而,在回调函数中操作该属性并没有达到预期的效果。

import os
from bokeh.models import ColumnDataSource, Patches
from bokeh.plotting import figure
from bokeh.layouts import row
from bokeh.io import output_file, curdoc
import pandas as pd

x = [[1,2,4], [3,5,6], [7,9,7], [5,7,6]]
y = [[4,2,1], [6,5,8], [3,9,6], [2,2,1]]
group = ['A', 'A', 'B', 'B']
id = [0,1,2,3]

df = pd.DataFrame(data=dict(x=x, y=y, group=group, id=id))
source = ColumnDataSource(df)

p = figure(tools="tap")

renderer = p.patches('x', 'y', source=source)

# Event handler
def my_tap_handler(attr,old,new):
global source
group_name = source.data['group'][new['1d']['indices'][0]]
group_indices = df['id'][df['group'] == group_name]
source.selected.indices = list(group_indices)
print("source.selected.indices", source.selected.indices)


selected_patches = Patches(fill_color="#a6cee3")
renderer.selection_glyph = selected_patches

# Event
renderer.data_source.on_change("selected", my_tap_handler)

#######################################
# Set up layouts and add to document
curdoc().add_root(row(p, width=800))

最佳答案

您可以在 Javascript 中进行选择,但如果您真的想在 Python 中进行此操作,这里有一个示例:

import os
from bokeh.models import ColumnDataSource, Patches, CustomJS
from bokeh.plotting import figure
from bokeh.layouts import row
from bokeh.io import output_file, curdoc
import pandas as pd

def app(doc):
x = [[1,2,4], [3,5,6], [7,9,7], [5,7,6]]
y = [[4,2,1], [6,5,8], [3,9,6], [2,2,1]]
group = ['A', 'A', 'B', 'B']
id = [0,1,2,3]

df = pd.DataFrame(data=dict(x=x, y=y, group=group, id=id))
source = ColumnDataSource(df)

p = figure(tools="tap")

renderer = p.patches('x', 'y', source=source)

def my_tap_handler(attr,old,new):
indices = source.selected.indices
if len(indices) == 1:
group = source.data["group"][indices[0]]
new_indices = [i for i, g in enumerate(source.data["group"]) if g == group]
if new_indices != indices:
source.selected = Selection(indices=new_indices)

selected_patches = Patches(fill_color="#a6cee3")
renderer.selection_glyph = selected_patches
source.on_change("selected", my_tap_handler)

doc.add_root(row(p, width=800))

show(app)

关于python - Bokeh 服务器 - 如何在回调函数中操作选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50492995/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com