@pn.depends on active tab

Hey,
I’m trying to build a dashboard with two tabs, each tab contains a plot function:

@pn.depends(int_widget.param.value)
plot_somethin(variable): #there is also plot_somethin2() for the other tab
returns a plot

that is dependent (pn.depends) on the same widget (not inside any of these tabs).
Due to the fact that these plotting functions take a lot of time I want the function for each tab to run only when that tab is active.
Is there any possible way that the plot_somthin will only run when that tab is active?

Thanks.

Welcome sahar540,

You would wrap your expensive plotting in pn.param.ParamFunction. From the docs:

import time
import numpy as np
import panel as pn
from bokeh.plotting import figure

pn.extension()

def plot():
    time.sleep(1) # some long running calculation
    np.random.seed(tabs.active)
    xs, ys = np.random.randn(2, 100)
    p = figure(width=300, height=300, name=f'Scatter Seed {tabs.active}')
    p.scatter(xs, ys)
    return p

p1 = pn.param.ParamFunction(plot, lazy=True, name='Seed 0')
p2 = pn.param.ParamFunction(plot, lazy=True, name='Seed 1')
p3 = pn.param.ParamFunction(plot, lazy=True, name='Seed 2')

tabs = pn.Tabs(p1, p2, p3, dynamic=True)

tabs

Thanks for the reply!
I Implemented this example, but while changing my int_widget value both tabs are computing and running their plots calculations
I thought of using tabs.active parameter with an IF statement but could wrap my brain around it.

Your approach with an IF statement could maybe look like this:

import time
import numpy as np
import panel as pn
from bokeh.plotting import figure
from functools import partial

pn.extension()

slider = pn.widgets.IntSlider(start=100, end=1000, step=100, value=100)

def plot(slider, active_tab, target_tab):
    if active_tab == target_tab:
        time.sleep(1) # some long running calculation
        np.random.seed(active_tab)
        xs, ys = np.random.randn(2, slider)
        p = figure(width=300, height=300, name=f'Scatter Seed {active_tab}')
        p.scatter(xs, ys)
        return p

tabs = pn.Tabs(dynamic=True)

p1 = ('Seed 0', pn.depends(slider.param.value, tabs.param.active)(partial(plot, target_tab=0)))
p2 = ('Seed 1', pn.depends(slider.param.value, tabs.param.active)(partial(plot, target_tab=1)))
p3 = ('Seed 2', pn.depends(slider.param.value, tabs.param.active)(partial(plot, target_tab=2)))
           

tabs.append(p1)
tabs.append(p2)
tabs.append(p3)

pn.Column(slider, tabs)

This works great, but tabs are disappearing after leaving each tab, never seen this before

Do you have any idea?

Hi @sahar540,

I cannot replicate the disappearing tab behavior with the provided example. Perhaps a bug could possibly have been introduced when you adapted it to another set of code. Without a reproducible example from you on the behavior, I can only speculate which won’t be helpful. I’m not sure where to take this without more info from you.

1 Like