How can I access values selected through a Stream

2019-08-23 11:17发布

问题:

I'm plotting and selecting points with Holoviews

import holoviews as hv
import numpy as np

N = 100
x = np.random.normal(size=N)
y = np.random.normal(size=N)

points = hv.Points((x, y))

selection = hv.streams.Selection1D(points)

points.options(tools=["lasso_select"])

How can I get the indices selected from lasso as a vector in my Python environment for further analysis?

回答1:

There's ample documentation, start for example here: http://holoviews.org/reference/streams/bokeh/Selection1D_tap.html

Basically, you need to link your selection stream to the holoviews element through a DynamicMap. Then, selection will hold your selected indices.

I adapted the following example from the docs:

import holoviews as hv
import numpy as np
hv.extension('bokeh')

N = 100
x = np.random.normal(size=N)
y = np.random.normal(size=N)

points = hv.Points((x, y))

selection = hv.streams.Selection1D(source=points, index=[0]) # set default arg

def process_selection(index):
    print(index)
    return hv.VLine(np.mean(x[index]))


dmap = hv.DynamicMap(process_selection, streams=[selection])

l = points * dmap

l.options(hv.opts.Points(tools=['tap'], size=10))

Then do some selection. Now print(selection) will hold the selected indices