๐ Day 5: Stacked Bar Chart in Python
๐ What is a Stacked Bar Chart?
A stacked bar chart displays bars on top of each other instead of side by side.
Each bar represents:
-
The total value of a category
-
The contribution of each sub-category within that total
This makes it easy to see both:
✔ Overall totals
✔ Individual contributions
✅ When Should You Use a Stacked Bar Chart?
Use a stacked bar chart when:
-
You want to show part-to-whole relationships
-
Total value and composition both matter
-
Comparing how components change across categories
Real-world examples:
-
Product-wise sales per year
-
Department-wise expenses
-
Male vs female population by year
๐ Example Dataset
Let’s visualize yearly sales of two products:
| Year | Product A | Product B |
|---|---|---|
| 2022 | 50 | 40 |
| 2023 | 70 | 60 |
| 2024 | 90 | 75 |
Each bar shows total yearly sales, while colors show Product A and Product B contributions.
๐ง Python Code: Stacked Bar Chart Using Matplotlib
๐งฉ Code Explanation (Simple)
plt.bar(x, product_a) → creates the base bars
bottom=product_a → stacks Product B on top of Product A
legend() → identifies each product
-
Total bar height = Product A + Product B
๐ Stacked Bar Chart vs Grouped Bar Chart
| Stacked Bar Chart | Grouped Bar Chart |
|---|
| Shows composition | Shows comparison |
| Highlights totals | Highlights differences |
| Parts stacked | Bars side by side |
๐ Key Takeaways
✔ Best for showing total + breakdown
✔ Useful for composition analysis
✔ Easy to understand trends in parts
.png)

0 Comments:
Post a Comment