Altair - Multiple lines chart using slider widget

Viewed 30

Starting with this dataframe I want to create an interactive chart, where 'x' column is an x-axis and the rest of the columns ('1'-'10') are functions plotted on y-axis.

My idea is to use slider widget to select multiple functions (so in default only one function is plotted, by using the slider you can plot more lines up to all 10 functions at once - so slider works not like simple selector, instead the selection is let say 'cumulative').

I'm completely new to Altair. So far I've managed to plot all the functions at once, but slider selector doesn't work at all.

data = df.melt('x')
chart = alt.Chart(data).mark_line().encode(
    x='x',
    y='value',
    color='variable'
)

slider = alt.binding_range(min=1, max=10, step=1)
slider_selection = alt.selection_single(bind=slider, fields=['variable'])

chart.add_selection(slider_selection).transform_filter(slider_selection)

Please help.

PS. Data are generated as follows:

n = 50
Xtest = np.linspace(-5, 5, n).reshape(-1,1)

def kernel(a, b, param):
    sqdist = np.sum(a**2,1).reshape(-1,1) + np.sum(b**2,1) - 2*np.dot(a, b.T)
    return np.exp(-.5 * (1/param) * sqdist)

param = 0.1
K_ss = kernel(Xtest, Xtest, param)
L = np.linalg.cholesky(K_ss + 1e-15*np.eye(n))
f_prior = np.dot(L, np.random.normal(size=(n,10)))

df = pd.DataFrame(f_prior)
df.columns += 1
df['x'] = Xtest
df.columns = df.columns.map(str)
2 Answers

your code works just fine. Only change you need to make - > check if the column 'variable' is actually an int...

data['variable']=data['variable'].astype(int)enter image description here

You can achieve this by using selection values in expressions:

data = df.melt('x')
data['variable'] = data['variable'].astype(int)

chart = alt.Chart(data).mark_line().encode(
    x='x',
    y='value',
    color='variable:N'
)

slider = alt.binding_range(min=1, max=10, step=1, name='Function ')
slider_selection = alt.selection_single(bind=slider, fields=['variable'], name='function_selections', init=1)

chart.add_selection(slider_selection).transform_filter('function_selections.variable >= datum.variable')

enter image description here

Related