pythonpython-3.xpanelholoviz

Plot doesnot change with drop down select


I am trying to build an interactive plot for dashboard. The data is in pandas dataframe state_df.

ty=['Confirmed','Bedridden','Recovered']

def type_tt(need_type):
    need=[]
    need.append(need_type)
    my_df=state_df[state_df.Status.isin(need)]
    my_df=my_df.set_index('Date')
    return my_df


def heat_map(types):
    num=10# 10 day
    my_df=type_tt(types)
    sns.heatmap((my_df.drop('Status',axis=1)).tail(num)[top_14],cmap='Blues', linewidths=0.1)
    #df.style.background_gradient(cmap='Blues')

#heat_map(types_op)
app7=pn.interact(heat_map,types=ty)
app7

This gives a drop-down menu with options enter image description here

But when I change the option from dropdown menu, the plot doesn't change. I tried looking into documentation for linking but nothing works out.

Any leads?


Solution

  • The most important thing to add here is that your function heat_map() needs to return your plot. I think that's what is missing.

    It's hard to recreate your example since there is no sample data, but here's an example that works. I've used hvplot instead of seaborn to create an interactive heatmap.

    Example code:

    # import libraries
    import numpy as np
    import pandas as pd
    import hvplot.pandas
    import panel as pn
    pn.extension()
    
    # create sample data
    df = pd.DataFrame({
        'date': pd.date_range(start='01-01-2020', end='31-12-2020'),
        'status': np.random.choice(['confirmed', 'bedridden', 'recovered'], 366),
        'status2': np.random.choice(['A', 'B', 'C'], 366),
        'value': np.random.rand(366) * 100
    })
    
    types = ['confirmed', 'bedridden', 'recovered']
    
    # you need to return your plot to get the interaction
    def plot_heatmap(chosen_type):
        df_selected = df[df['status']==chosen_type]
        # hvplot is handy for creating interactive plots
        heatmap = df_selected.hvplot.heatmap(x='date', y='status2', C='value')
        return heatmap
    
    # show your interactive plot with dropdown   
    pn.interact(plot_heatmap, chosen_type=types)
    

    As a sidenote, with hvplot you wouldn't need all this extra code to get a decent interactive heatmap with dropdown. You could just do:

    df.hvplot.heatmap(x='status2', y='date', C='value', groupby='status')
    

    More info on pn.interact():
    https://panel.holoviz.org/getting_started/index.html

    Resulting interactive plot with dropdown: interactive heatmap with dropdown