2015-12-08 43 views
5

如果散景中有散點圖,並且啓用了框選工具,假設我使用框選工具選擇幾個點。我如何訪問我選擇的點的(x,y)位置信息?獲取包含在散景框中的框選工具中的選定數據

%matplotlib inline 
import numpy as np 
from random import choice 
from string import ascii_lowercase 

from bokeh.models.tools import * 
from bokeh.plotting import * 

output_notebook() 


TOOLS="pan,wheel_zoom,reset,hover,poly_select,box_select" 
p = figure(title = "My chart", tools=TOOLS) 
p.xaxis.axis_label = 'X' 
p.yaxis.axis_label = 'Y' 

source = ColumnDataSource(
    data=dict(
     xvals=list(range(0, 10)), 
     yvals=list(np.random.normal(0, 1, 10)), 
     letters = [choice(ascii_lowercase) for _ in range(10)] 
    ) 
) 
p.scatter("xvals", "yvals",source=source,fill_alpha=0.2, size=5) 

select_tool = p.select(dict(type=BoxSelectTool))[0] 

show(p) 

# How can I know which points are contained in the Box Select Tool? 

我不能叫「回調」屬性和「尺寸」屬性只返回一個列表[「寬度」,「高度」]。如果我只能得到所選框的尺寸和位置,我可以從那裏算出我的數據集中的哪些點。

回答

9

您可以與所選數據的索引更新一個Python變量ColumnDataSource使用callback

%matplotlib inline 
import numpy as np 
from random import choice 
from string import ascii_lowercase 

from bokeh.models.tools import * 
from bokeh.plotting import * 
from bokeh.models import CustomJS 



output_notebook() 


TOOLS="pan,wheel_zoom,reset,hover,poly_select,box_select" 
p = figure(title = "My chart", tools=TOOLS) 
p.xaxis.axis_label = 'X' 
p.yaxis.axis_label = 'Y' 

source = ColumnDataSource(
    data=dict(
     xvals=list(range(0, 10)), 
     yvals=list(np.random.normal(0, 1, 10)), 
     letters = [choice(ascii_lowercase) for _ in range(10)] 
    ) 
) 
p.scatter("xvals", "yvals",source=source,fill_alpha=0.2, size=5) 

select_tool = p.select(dict(type=BoxSelectTool))[0] 

source.callback = CustomJS(args=dict(p=p), code=""" 
     var inds = cb_obj.get('selected')['1d'].indices; 
     var d1 = cb_obj.get('data'); 
     console.log(d1) 
     var kernel = IPython.notebook.kernel; 
     IPython.notebook.kernel.execute("inds = " + inds); 
     """ 
) 

show(p) 

然後你就可以訪問所需的數據屬性使用類似

zip([source.data['xvals'][i] for i in inds], 
    [source.data['yvals'][i] for i in inds]) 
+0

真棒!我只需將CustomJS更改爲「回調」(仍然具有0.9.0版本)。感謝您的幫助,真的很有用。 –

+1

@FrankFineis:很高興幫助!隨時點擊(點擊三角形)並接受答案(通過點擊勾號)從「未答覆」列表中刪除問題(並給我一些互聯網點'=)') – Jake