I have a dash application where I am filtering data and then plotting it with following code:
def filter_dataframe(selected_racetracks, selected_bops):
filtered_df = df_bop.copy() # Initialize with original DataFrame
# Perform data filtering based on left-hand side filter
filtered_df = filtered_df.loc[(filtered_df['racetrack'] == selected_racetracks[0])]
# Check if selected_bops is None or empty list
if not selected_bops[0] is None:
filtered_df = filtered_df[filtered_df['bop'] == selected_bops[0]]
# Get the first racetrack from the list
racetrack_str = selected_racetracks[0] if selected_racetracks else None
# Check if the filtered DataFrame is empty
if filtered_df.empty:
# Return an empty figure if the filtered DataFrame is empty
return {'data': [], 'layout': {}}
# ==================== Figure 1 ================================
fig_weight = px.bar(
filtered_df,
x='make_model',
y='total_weight_wo_driver',
barmode='group',
color='bop_date',
template="plotly_dark",
text="total_weight_wo_driver",
)
# Additional traces for the second and third rows of filters
for racetrack, bop in zip(selected_racetracks[0:], selected_bops[0:]):
if racetrack and bop:
filtered_df_additional = df_bop[(df_bop['racetrack'] == racetrack) & (df_bop['bop'] == bop)]
date_string = datetime.strptime(filtered_df_additional['bop_date'].unique()[0], '%Y.%m.%d').strftime('%Y.%m.%d')
bar_text = filtered_df_additional['total_weight_wo_driver']
if not filtered_df_additional.empty:
fig_weight.add_bar(
x=filtered_df_additional['make_model'],
y=filtered_df_additional['total_weight_wo_driver'],
name=date_string, # set trace name
text=bar_text
)
fig_weight.update_xaxes(
tickangle=-70)
fig_weight.update_layout(
title_text=racetrack_str + " BOP total weight evolution",
title_xanchor="left",
barmode='group',
yaxis_range=[1200, 1400],
height=600,
title_font=dict(size=24)
)
return fig_weight
My problem is that, when I am using the Addition traces part, everything is working fine but the generated bar charts are overlaying the first chart, like you can see below:
Are there any usefull hints in solving this issue?
I have tried to generate the figure directly within the loop, but then I am getting an error that the graph can not be done.
Thank you for the help!