Skip to content

Conversation

@AJSTYLE-lab
Copy link

Pull Request Description for #5428

Title:
Fix stacked barplot missing groups issue (#5428)

Description:
This PR addresses the bug where certain groups (commanders) with non-missing values are not displayed in stacked bar plots when using plotly.express.bar.

Problem:

When plotting a stacked bar chart of commander_perc_of_card vs. savedate_week, some commanders with values for certain weeks were missing in the overall plot.

This happens because plotly.express.bar only plots groups that exist for each specific x value (savedate_week). Missing combinations are ignored, even if other weeks have values.

Solution:

Generated all possible combinations of savedate_week and commanders using itertools.product.

Merged these combinations with the original dataset.

Filled missing commander_perc_of_card values with 0 to ensure that every commander is displayed for every week.

This guarantees that stacked barplots now show all groups, maintaining accurate visual representation.

Files Modified:

reproduce_bug.py — added a reproducible example to demonstrate the fix.

Before

Image

After

Image

Code:

importpandasaspdimportplotly.expressaspxfromitertoolsimportproduct# Load the dataplot_data=pd.read_csv("example_plot_data.csv") plot_data['savedate_week'] =pd.to_datetime(plot_data['savedate_week']) # Get all unique weeks and commandersall_weeks=plot_data['savedate_week'].unique() all_commanders=plot_data['commanders'].unique() # Generate full combinations of weeks and commandersfull_index=pd.DataFrame(list(product(all_weeks, all_commanders)), columns=['savedate_week','commanders']) # Merge with original data and fill missing values with 0plot_data_full=full_index.merge(plot_data, on=['savedate_week','commanders'], how='left') plot_data_full['commander_perc_of_card'] =plot_data_full['commander_perc_of_card'].fillna(0) # Create the stacked barplotfig=px.bar( plot_data_full, x="savedate_week", y="commander_perc_of_card", color="commanders" ) fig.show()

@camdecoster
Copy link
Contributor

Thanks for the PR! One of our team members will review and provide feedback.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@AJSTYLE-lab@camdecoster@emilykl