Make it interactive using panel

We can make the plot interactive using panel. we need to reformat our print function to a general function that can handle year 2019, 2020 or both and we need to create a widget to select the years. We will make a grid layout to display the widget, the plot and the table. First we make sure we can run the panel form the notebook by panel.extension()

Important! If you use matplotlib instead of bokeh or holov you must make sure to return an interactive plot using pn.pane.Matplotlib(fig)

import panel as pn
pn.extension()
#generalize function
def plot_sales(labels = df_sales['month'], location = " Drenthe", years = ['2020']):
    width = 0.35  # the width of the bars
    fig, ax = plt.subplots()
    
    n = len(years)
    x = np.arange(len(labels))
    pos = x - width/n
    
    color = {'2019':'lightgrey', '2020':'grey'} 
    
    for year in years:
        sales = df_sales[int(year)]
        ax.bar(pos, sales, width, label=year, color = color[year])
        pos = pos + width

    ax.set_ylabel('gemiddeld aantallen verkocht')
    ax.set_title('Verkoop in' + location)
    ax.legend()
    ax.set_xticks(x)
    ax.set_xticklabels(labels)
    plt.gcf().autofmt_xdate(rotation=90, which = 'major', ha="center")
    plt.figsize=(8, 6)
    fig.tight_layout()
    ########## return a panel object! ########
    mpl_pane = pn.pane.Matplotlib(fig)

    return mpl_pane
#create the widget
checkbox_group = pn.widgets.CheckBoxGroup(
    name='Checkbox Group', value=['2020'], options=['2019', '2020'],
    inline=True)
#connect the widget to the function
ip = pn.interact(plot_sales, years = checkbox_group)
#desing grid
salesgrid = pn.GridSpec(sizing_mode='stretch_both', max_height=800)
salesgrid[0,0] = ip[1]
salesgrid[0,1] = pn.pane.DataFrame(df_sales)
salesgrid[1,0] = ip[0]
salesgrid.show()
bare panel dashboard

Making the panel nice with a template

The code generates interactive plots but is does not look nice. Let us use a template. See https://panel.holoviz.org/user_guide/Templates.html

dashboard = pn.template.BootstrapTemplate(title='My awesome dashboard', sidebar_width=200)
dashboard.sidebar.append(ip[0])
dashboard.main.append(pn.Row(ip[1],pn.pane.DataFrame(sales_pivoted)))
dashboard.show()
Launching server at http://localhost:56292
panel dashboard with template

Last updated

Was this helpful?