Python Panel passing dataframe to param.Parameterized

Question:

Python Panel passing a dataframe in param.Parameterized class

I can build a dashboard using panel. I know want to include the code in a class including the data manipulation.

    df = ydata.load_web(rebase=True)
    class Plot(param.Parameterized):
        df = df
        col = list(df.columns)
        Index1 = param.ListSelector(default=col, objects=col)
        Index2 = param.ListSelector(default=col[1:2], objects=col)

        def dashboard(self, **kwargs):
            unds = list(set(self.Index1 + self.Index2))
            return self.df[unds].hvplot()

    b = Plot(name="Index Selector")
    pn.Row(b.param, b.dashboard)

I would like to call

   b =  Plot(name="Index Selector", df=ydata.load_web(rebase=True))
Asked By: Michel Latch

||

Answers:

Using a parameterized DataFrame and two methods for

  • setting the ListSelector according the available columns in the data frame and
  • creating a plot with hv.Overlay (containing single plots for each choosen column),

the code could look like this:

# Test data frame with two columns
df = pd.DataFrame(np.random.randint(90,100,size=(100, 1)), columns=['1'])
df['2'] = np.random.randint(70,80,size=(100, 1))

class Plot(param.Parameterized):
    df = param.DataFrame(precedence=-1) # precedence <1, will not be shown as widget
    df_columns = param.ListSelector(default=[], objects=[], label='DataFrame columns')

    def __init__(self, **params):
        super(Plot, self).__init__(**params)

        # set the column selector with the data frame provided at initialization
        self.set_df_columns_selector() 

    # method is triggered each time the data frame changes
    @param.depends('df', watch=True)
    def set_df_columns_selector(self):
        col = list(self.df.columns)
        print('Set the df index selector when the column list changes: {}'.format(col))
        self.param.df_columns.objects = list(col) # set choosable columns according current df
        self.df_columns = [self.param.df_columns.objects[0]] # set column 1 as default

    # method is triggered each time the choosen columns change
    @param.depends('df_columns', watch=True)
    def set_plots(self):
        print('Plot the columns choosen by the df column selector: {}'.format(self.df_columns))
        plotlist = [] # start with empty list
        for i in self.df_columns:
            # append plot for each choosen column
            plotlist.append(hv.Curve({'x': self.df.index, 'y':self.df[i]}))
        self.plot = hv.Overlay(plotlist)

    def dashboard(self):
        return self.plot

b = Plot(name="Plot", df=df)

layout = pn.Row(b.param, b.dashboard)
layout.app()
#or:
#pn.Row(b.param, b.dashboard)

This way the parameterized variables take care of updating the plots.

Answered By: mdk