VScode notebook creates new chart for every click of checkbox

Newbie question. Starting my dashboard by creating a chart with selectable series using panel in VScode notebook.

Code cell is:

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

nselect = pn.widgets.Checkbox(name='nsw',value = True)
vselect = pn.widgets.Checkbox(name='vic')
mypane = pn.Pane
bound_plot = pn.bind(price_plot, nsw=nselect, vic=vselect)
pn.Column(nselect, vselect,  bound_plot)

price_plot function code is:

def price_plot(nsw,vic):
    cstate = []
    if nsw: cstate.append("nsw")
    if vic: cstate.append("vic")
    return spri[cstate].groupby(level =[0]).mean().plot()

Runs fine on first run:

But every time a check box is ticked or unticked a new figure is produced. I was expecting the original figure to adjust but maybe I, as an amateur, just don’t understand how it works? I can only upload one image but in words when I check the “vic” box a new chart is drawn below the original figure with “nsw” and “vic” series

If I recall correctly, for a “live” connection in the notebook, you need to add a few more things, which can be found in the docs, I forgot the exact section.

Thanks. I have looked in the docs, and there is a bit to read, but I am clearly missing something. Maybe I need to put the “live” connection into a browser window.

What if you import hvplot.pandas

and do

spri[cstate].groupby(level =[0]).mean().hvplot()



pn.panel(spri[cstate].groupby(level =[0]).mean().plot())

Problem solved. Thanks for the assistance. The answer was found in the docs and was a matter of returning “fig” from the function rather than the ax sub object. The working code is:

def price_plot(nsw,vic):
    plt.style.use (matplotx.styles.dracula)
    fig, ax = plt.subplots()
    cstate = []
    if nsw: cstate.append("nsw")
    if vic: cstate.append("vic")
    ax.plot(spri[cstate].groupby(level =[0]).mean())
    return fig
1 Like