Plotly express dropdown menu between 2 dataframes

I have 2 dataframes which I need to display using plotly express. I’d like to put a dropdown menu on my bar chart, where I could select beween years using df[β€˜year’] values.

what my data look like:

import pandas as pd
import plotly.express as px

data_2023 = {
    'country': ['CE', 'CE', 'CE', 'CE', 'CE', 'CZ', 'CZ', 'CZ', 'CZ', 'CZ', 'HU', 'HU', 'HU', 'HU', 'HU', 'SK', 'SK', 'SK', 'SK', 'SK'],
    'category': ['BABY']*20,
    'repl_types': ['full_pallet', 'mu', 'nsrp', 'split_pallet', 'srp']*4,
    'period': ['p11']*20,
    'value': [137.0, 0.0, 79686.0, 76.0, 86973.0,
              137.0, 0.0, 23453.0, 76.0, 34163.0,
              0.0, 0.0, 34060.0, 0.0, 23228.0,
              0.0, 0.0, 22173.0, 0.0, 29582.0],
    'value_%': [0.000821, 0.0, 0.477528, 0.000455, 0.521196,
                0.002369, 0.0, 0.405558, 0.001314, 0.590759,
                0.0, 0.0, 0.594540, 0.0, 0.405460,
                0.0, 0.0, 0.428422, 0.0, 0.571578],
'year': [2023]*20,
}

data_2024 = {
    'country': ['CE', 'CE', 'CE', 'CE', 'CE', 'CZ', 'CZ', 'CZ', 'CZ', 'CZ', 'HU', 'HU', 'HU', 'HU', 'HU', 'SK', 'SK', 'SK', 'SK', 'SK'],
    'category': ['BABY']*20,
    'repl_types': ['full_pallet', 'mu', 'nsrp', 'split_pallet', 'srp']*4,
    'period': ['p11']*20,
    'value': [100000, 0, 50000, 0, 140000,
              50000, 0, 70000, 0, 100000,
              0, 0, 80000, 0, 50000,
              0, 0, 90000, 0, 60000],
}

data_2024 = pd.DataFrame(data)
data_2024['value_%'] = data_2024 .groupby('country')['value'].apply(lambda x: x / x.sum())
data_2024['year'] = 2024

and here is my plotly I need (only for data_2023 currently):

for x in data_2023['category'].unique().tolist():

    fig = px.bar(data_2023[data_2023.category.isin([x])], x="period", y="value_%",
                 color='repl_types', barmode='stack', facet_col='country',text_auto='.0%', color_discrete_sequence=["#5497c7", "green", "#c74848", "goldenrod", "#5f48c7"],
                       opacity=0.8, facet_row_spacing =0.08,# color_discrete_sequence=px.colors.qualitative.Alphabet,
                  height=400,
                 width = 1800,
                 category_orders={"country": ["CZ", "HU", "SK", "CE"]},
                 title=f'{x}',facet_col_wrap=5, orientation='v')

    
    fig.update_traces(textfont_size=12, textangle=0, textposition="auto", cliponaxis=False)
    fig.update_yaxes(matches=None)
    fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1], font_size=18))
    fig.update_yaxes(title_font_color='white')
    for annotation in fig['layout']['annotations']: 
        annotation['textangle']= 0
    fig.update_layout(title_text=f"<b>{x}</b>")
    fig.update_layout(legend=dict(
                orientation="h",
                yanchor="bottom",
                y=1.1,
                xanchor="right",
                x=1.1))
   fig.show()

Could you please help me how to get this dropdown menu? thanks a lot in advance

Hey @phrubos welcome to the forums.

Here some helpful information:

An easier example as in the provided link (IMHO):

import plotly.graph_objects as go
import numpy as np

x = np.arange(10)
y_0 = np.random.randint(0,10,10)
y_1 = np.random.randint(0,10,10)

# base figure
fig = go.Figure(go.Scatter(x=x, y=y_0, visible=True)) 

# buttons to create
buttons = [
    {
        'method': 'restyle',
        'label': 'data 0',
        'visible': True,
        'args': [
            {
                'x': [x],
                'y': [y_0],
                'type':'scatter'
            }, 
            [0]
        ]
    },
    {
        'method': 'restyle',
        'label': 'data 1',
        'visible': True,
        'args': [
            {
                'x': [x],
                'y': [y_1],
                'type':'scatter'
            }, 
            [0]
        ]
    }
]

# Add dropdown
updatemenu=[
    {
        'buttons': buttons,
        'direction': 'down',
        'showactive': True
    }
]
fig.update_layout(updatemenus=updatemenu)

tabs
mrep dropdown

1 Like