Search code examples
pandasbokehpanelholoviewshvplot

HoloViews: create boxplots interactive


I'd like to create a Dashboard where the user can choose which data is shown in a Boxplot via chosing by button. All I could find where instructions for linear-interactive plots, unfortunately i am not able to find out how to make interactive boxplots.

so far my code looks like this:

import numpy as np
import hvplot.pandas 
import panel as pn 
import holoviews as hv

np.random.seed(1234)
adf = pd.DataFrame(np.random.rand(3, 4),
                  columns=['Col1', 'Col2', 'Col3', 'Col4'])

bdf = pd.DataFrame(np.random.rand(3, 4),
                  columns=['Col1', 'Col2', 'Col3', 'Col4'])

adf['Type'] = 'A'
bdf['Type'] = 'B'
df = pd.concat([adf,bdf])
df.index.names = ['idx']

That's my DataFrame:

idx Col1        Col2        Col3        Col4        Type
0   0.191519    0.622109    0.437728    0.785359    A
1   0.779976    0.272593    0.276464    0.801872    A
2   0.958139    0.875933    0.357817    0.500995    A
0   0.683463    0.712702    0.370251    0.561196    B
1   0.503083    0.013768    0.772827    0.882641    B
2   0.364886    0.615396    0.075381    0.368824    B

created some buttons:


typebutton = pn.widgets.RadioButtonGroup(name='Typebutton', options=['A','B'],button_type='success')

and now connect the buttons with the dataframe:

df = df.interactive()
df_inter = (df[df.Type == typebutton]) 

Interactive DataFrame with buttons

now i prepare for plotting:


df_group = df_inter.groupby(['idx'])[['Col1', 'Col2', 'Col3', 'Col4']].mean()

and at this point i can use

dfplot = df_group.hvplot()

for getting an interactive linear plot of my Data. But how can I create Interactive Boxplots?

So far i know that:

hv.BoxWhisker(bdf.melt(), kdims='variable', vdims='value')

Is giving me the Boxplots, but how do i make them interactive?


Solution

  • Box plots are supported by hvPlot; no need to drop down to HoloViews. See https://hvplot.holoviz.org/reference for all the plot types supported. Note that the .hvplot.box() syntax listed on the web pages is not yet supported for .interactive; you need to call it as kind='box' instead:

    import numpy as np, pandas as pd, hvplot.pandas, panel as pn
    np.random.seed(1234)
    cols = ['Col1', 'Col2', 'Col3', 'Col4']
    adf = pd.DataFrame(np.random.rand(3, 4), columns=cols)
    bdf = pd.DataFrame(np.random.rand(3, 4), columns=cols)
    adf['Type'] = 'A'
    bdf['Type'] = 'B'
    
    df = pd.concat([adf,bdf])
    df.index.names = ['idx']
    
    typebutton = pn.widgets.RadioButtonGroup(name='Typebutton', options=['A','B'],button_type='success')
    dfi = df.interactive(width=800)
    df_inter = (dfi[dfi.Type == typebutton])
    df_inter.hvplot(kind='box')
    

    radio-box selected box plots