MatplotlibXBy @CodeWithMunnaX
Catalog
Track: Essential Charts
Categorical Data14 mins

12. Grouped & Stacked Bar Charts

When each category contains sub-groups (e.g. Q1-Q4 revenue broken down into Product A vs Product B), grouped and stacked bar charts provide multi-dimensional comparisons.

Mental Model Intuition

Grouped: Standing two athletes shoulder-to-shoulder. Stacked: Standing one athlete on top of the other's shoulders.

Core Concepts & Mechanics

The `bottom` Parameter for StackingStacking

Setting `bottom=product_a` offsets the base of product B's bars by product A's height.

Stacking visualizes both individual segment size and total sum simultaneously.
plt.bar(cats, b_vals, bottom=a_vals)
Grouped Bars via Numerical OffsetsGrouped

Grouped bars require computing offset numerical coordinates `x - width/2` and `x + width/2` using `np.arange()`.

Shift X coordinates left and right by half the bar width so they sit side-by-side without overlapping.
x = np.arange(len(cats)) plt.bar(x - 0.2, y1, width=0.4) plt.bar(x + 0.2, y2, width=0.4)

Common Beginner Mistakes & Pro Fixes

Avoid the top errors and bad plotting practices that trip up new Python developers

Troubleshooting

Quick Lesson Takeaways

  • Use `bottom=base_series` to stack bars vertically.
  • Use `x - width/2` and `x + width/2` with `plt.xticks()` for grouped bars.
  • Stacked bars show totals; grouped bars make cross-group comparison easier.
Topic 12 • Python IDE
Python 3.12 • Matplotlib
Run Python code to inspect terminal output.

Real-World Datasets (1-Click Switcher)

Switch from abstract numbers to relatable Cricket, Cinema & Business charts

5 Curated Datasets

Hands-on Challenge: Create a Stacked Bar Chart

+50 XP

Write Matplotlib code to solve the objective and see your live plot render

Objective Instructions:

Create a stacked bar chart for `cats=['A', 'B']` with `base=[10, 20]` (color='#6366F1') and `top=[5, 15]` (color='#00D9C0') using `bottom=base`.

Required Keywords:✓ bottom✓ plt.bar
Challenge Code Editor
Challenge Output GraphLive Vector Preview
Write code on the left to render live challenge plot
End of Lesson Knowledge Check

Quick Mini Quiz: 2 Concept Questions

Test your understanding to unlock the lesson completion badge

Q1

Which Matplotlib function is used to create a standard continuous 2D line plot?

Q2

What must you call after specifying label='...' so that the legend actually appears on the canvas?

0 of 2 answered