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