Holoviews, overlay a different VLine for each frame of a HoloMap

Viewed 579

I am trying using the following code to create a scatter plot together with a vertical line of the mean of x axis values but I need some help how to achieve it.

import pandas as pd
import holoviews as hv
hv.extension('bokeh')

df = pd.DataFrame({'group': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   'x': [3, 4, 5, 2, 2, 3, 5, 4, 7],
                   'y': [10, 8, 9, 3, 7, 6, 5, 4, 8]})

m1 = df['x'].mean()
line1 = hv.VLine(m1)
line1.opts(color='red', line_dash='dashed')    
ds = hv.Dataset(df, kdims=['group'], vdims=['x', 'y'])
scatter = ds.to(hv.Scatter, 'x', 'y')
scatter.opts(width=400, height=400, size=10,
             tools=['hover'], xlim=(0, 11), ylim=(0, 11))
layout = scatter * line1
hv.save(layout, 'means0.html')

enter image description here It works fine as expected with the scatter plot and when changing the 'group' dimension changes the points plotted but the vertical line of the mean is calculated once for the whole dataframe and I don't know how to achieve interactivity for that element too. Meaning whenever I will change the 'group' dimension to calculate the mean for the selected 'group' and plot it as is does for the points.

1 Answers

You were almost there, you just had to put each VLine (with the mean of the subset accordingly calculated) into the HoloMap. The following explicitly inits the HoloMap through a dict.

import pandas as pd
import holoviews as hv
hv.extension('bokeh')

df = pd.DataFrame({'group': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   'x': [3, 4, 5, 2, 2, 3, 5, 4, 7],
                   'y': [10, 8, 9, 3, 7, 6, 5, 4, 8]})
hm = hv.HoloMap({
    group: hv.Scatter(df.loc[df.group==group], 'x', 'y') * hv.VLine(df.loc[df.group==group, 'x'].mean())
    for group in df.group.unique()
})

hm.opts(
    opts.Scatter(width=400, height=400, size=10,
                 tools=['hover'], xlim=(0, 11), ylim=(0, 11)),
    opts.VLine(color='red', line_dash='dashed') 
)
Related