Reuse plotting function with pn.rx() and hvplot

Hi everyone,

I’m working on a project where I’m trying to reuse a plotting function across multiple reactive DataFrames. These DataFrames are filtered using a Date Slider. However, when I change the value of the slider, I encounter an UnknownReferenceError.

Could anyone point me in the right direction on how to resolve this issue?

Thank you! :slight_smile:

Below is a minimal reproducible example of the problem:

import pandas as pd
import numpy as np
import hvplot.pandas
import panel as pn

# Example-Data
np.random.seed(42)
date_range = pd.date_range(start='2023-01-01', periods=100, freq='D')
df = pd.DataFrame({
    'Date': date_range,
    'Investment': np.random.randint(1000, 5000, size=100),
    'Delta': np.random.randint(100, 1000, size=100),
    'Market_Value': np.random.randint(5000, 10000, size=100)
}).set_index('Date')

##

# Date-Slider
min_date = df.index.min()
max_date = df.index.max()

date_slider = pn.widgets.DateSlider(
    name='Date', 
    start=min_date, 
    end=max_date, 
    value=max_date, 
    as_datetime=True)

# Reactive DataFrames
rdf_1 = pn.rx(df)
rdf_2 = pn.rx(df)

# Apply Filters
rdf_1 = rdf_1[rdf_1.index <= date_slider.param.value]
rdf_2 = rdf_2[rdf_2.index < date_slider.param.value]

##

# Plot-Function
def plot_function(df):
    plot_area = df.hvplot(
        kind='area',
        stacked=True,
        y=["Investment", "Delta"])

    plot_line = df.hvplot(
        kind="line", 
        y=["Market_Value", "Investment"], 
        line_width=1.5)
    
    plot = (plot_area * plot_line).opts(shared_axes=False)

    return pn.pane.HoloViews(plot, sizing_mode="stretch_both")

# Gridspec
grid = pn.GridSpec(sizing_mode='stretch_both', min_height=400)
grid[0, 0] = date_slider
grid[1, 0] = plot_function(rdf_1)
grid[1, 1] = plot_function(rdf_2)

grid