Bird
Raised Fist0
Matplotlibdata~15 mins

Horizontal grouped bars in Matplotlib - Deep Dive

Choose your learning style10 modes available
Overview - Horizontal grouped bars
What is it?
Horizontal grouped bars are a type of bar chart where bars are drawn horizontally and grouped side-by-side to compare multiple categories across different groups. Each group contains bars representing different sub-categories, aligned horizontally for easy comparison. This visualization helps show relationships and differences clearly when categories have multiple sub-groups. It is especially useful when category names are long or when comparing multiple series side by side.
Why it matters
Without horizontal grouped bars, comparing multiple categories with sub-groups can be confusing or cluttered, especially if category labels are long or if vertical space is limited. This chart type makes it easier to see differences and patterns across groups at a glance, improving decision-making and communication. It helps businesses, researchers, and analysts quickly understand complex data with multiple dimensions.
Where it fits
Before learning horizontal grouped bars, you should understand basic bar charts and how to plot simple horizontal bars in matplotlib. After mastering this, you can explore stacked bars, grouped bars with vertical orientation, and advanced customization like annotations and interactive plots.
Mental Model
Core Idea
Horizontal grouped bars arrange multiple related bars side-by-side along the horizontal axis to compare sub-categories within each main category clearly.
Think of it like...
Imagine a row of bookshelves where each shelf represents a category, and on each shelf, different colored books represent sub-categories placed side by side for easy comparison.
Categories ──────────────▶
┌─────────────────────────────┐
│ Group 1: ███ ████ ██        │
│ Group 2: █████ ██ ███       │
│ Group 3: ██ ██████ █        │
└─────────────────────────────┘
Bars run horizontally, grouped by category rows.
Build-Up - 6 Steps
1
FoundationBasic horizontal bar chart
🤔
Concept: Learn how to create a simple horizontal bar chart using matplotlib.
import matplotlib.pyplot as plt categories = ['A', 'B', 'C'] values = [5, 7, 3] plt.barh(categories, values) plt.xlabel('Value') plt.ylabel('Category') plt.title('Simple Horizontal Bar Chart') plt.show()
Result
A horizontal bar chart with three bars labeled A, B, and C, showing values 5, 7, and 3 respectively.
Understanding how to plot horizontal bars is the foundation for creating grouped horizontal bars later.
2
FoundationUnderstanding bar positioning
🤔
Concept: Learn how bar positions are controlled on the axis and how to adjust them.
import matplotlib.pyplot as plt import numpy as np categories = ['A', 'B', 'C'] values1 = [5, 7, 3] values2 = [6, 2, 4] indices = np.arange(len(categories)) plt.barh(indices, values1, height=0.4, label='Group 1') plt.barh(indices + 0.4, values2, height=0.4, label='Group 2') plt.yticks(indices + 0.2, categories) plt.xlabel('Value') plt.title('Bar Positioning Example') plt.legend() plt.show()
Result
Two sets of horizontal bars appear side by side for each category, showing how shifting positions controls grouping.
Knowing how to shift bar positions along the axis is key to grouping bars horizontally.
3
IntermediateCreating horizontal grouped bars
🤔Before reading on: do you think you can group bars horizontally by shifting their positions on the y-axis or x-axis? Commit to your answer.
Concept: Combine multiple horizontal bars per category by adjusting their vertical positions to create groups.
import matplotlib.pyplot as plt import numpy as np categories = ['A', 'B', 'C'] values1 = [5, 7, 3] values2 = [6, 2, 4] values3 = [4, 5, 6] indices = np.arange(len(categories)) bar_height = 0.2 plt.barh(indices - bar_height, values1, height=bar_height, label='Group 1') plt.barh(indices, values2, height=bar_height, label='Group 2') plt.barh(indices + bar_height, values3, height=bar_height, label='Group 3') plt.yticks(indices, categories) plt.xlabel('Value') plt.title('Horizontal Grouped Bars') plt.legend() plt.show()
Result
A horizontal grouped bar chart with three bars per category, grouped side by side horizontally.
Shifting bars vertically by small amounts creates clear groups, enabling comparison of multiple series per category.
4
IntermediateCustomizing colors and labels
🤔Before reading on: do you think adding colors and labels improves clarity or just adds decoration? Commit to your answer.
Concept: Use colors and labels to make groups distinct and easier to interpret.
import matplotlib.pyplot as plt import numpy as np categories = ['A', 'B', 'C'] values1 = [5, 7, 3] values2 = [6, 2, 4] values3 = [4, 5, 6] indices = np.arange(len(categories)) bar_height = 0.2 colors = ['#1f77b4', '#ff7f0e', '#2ca02c'] plt.barh(indices - bar_height, values1, height=bar_height, color=colors[0], label='Group 1') plt.barh(indices, values2, height=bar_height, color=colors[1], label='Group 2') plt.barh(indices + bar_height, values3, height=bar_height, color=colors[2], label='Group 3') plt.yticks(indices, categories) plt.xlabel('Value') plt.title('Colored Horizontal Grouped Bars') plt.legend() plt.show()
Result
Bars are colored distinctly per group, with a legend explaining each color, improving readability.
Colors and legends help viewers quickly identify groups and understand the chart without confusion.
5
AdvancedAdding value labels on bars
🤔Before reading on: do you think adding numeric labels on bars makes the chart cluttered or more informative? Commit to your answer.
Concept: Display numeric values on each bar to provide exact data points alongside visual comparison.
import matplotlib.pyplot as plt import numpy as np categories = ['A', 'B', 'C'] values1 = [5, 7, 3] values2 = [6, 2, 4] values3 = [4, 5, 6] indices = np.arange(len(categories)) bar_height = 0.2 colors = ['#1f77b4', '#ff7f0e', '#2ca02c'] bars1 = plt.barh(indices - bar_height, values1, height=bar_height, color=colors[0], label='Group 1') bars2 = plt.barh(indices, values2, height=bar_height, color=colors[1], label='Group 2') bars3 = plt.barh(indices + bar_height, values3, height=bar_height, color=colors[2], label='Group 3') plt.yticks(indices, categories) plt.xlabel('Value') plt.title('Horizontal Grouped Bars with Labels') plt.legend() for bars in [bars1, bars2, bars3]: for bar in bars: width = bar.get_width() plt.text(width + 0.1, bar.get_y() + bar.get_height()/2, f'{width}', va='center') plt.show()
Result
Each bar shows its numeric value at the end, making exact comparisons easy.
Adding labels balances visual and numeric information, aiding precise interpretation.
6
ExpertHandling uneven group sizes and spacing
🤔Before reading on: do you think grouped bars must always have the same number of bars per group? Commit to your answer.
Concept: Learn how to plot grouped bars when groups have different numbers of sub-categories and how to adjust spacing for clarity.
import matplotlib.pyplot as plt import numpy as np categories = ['A', 'B', 'C'] values = { 'Group 1': [5, 7], 'Group 2': [6, 2, 4], 'Group 3': [4] } max_bars = max(len(v) for v in values.values()) indices = np.arange(len(categories)) bar_height = 0.15 for i, (group, vals) in enumerate(values.items()): positions = indices - (bar_height * (len(vals) - 1) / 2) + i * bar_height plt.barh(positions[:len(vals)], vals, height=bar_height, label=group) plt.yticks(indices, categories) plt.xlabel('Value') plt.title('Grouped Bars with Uneven Sizes') plt.legend() plt.show()
Result
Bars are grouped horizontally with different numbers of bars per category, spaced evenly for readability.
Handling uneven group sizes requires dynamic positioning to maintain clear grouping and avoid overlap.
Under the Hood
Matplotlib draws horizontal bars by plotting rectangles along the y-axis positions with widths representing values. Grouping bars horizontally involves calculating y-axis positions for each bar within a category, offsetting them by a fixed height to avoid overlap. The bar height controls thickness, and the y-ticks are adjusted to label the center of each category group. Internally, matplotlib uses patches.Rectangle objects for bars, and the rendering engine draws them in order.
Why designed this way?
This design allows flexible control over bar placement and size, enabling grouped bars by simply shifting positions. It avoids complex layout engines by relying on numeric axis positioning. Alternatives like stacked bars overlay bars vertically, but grouping side-by-side requires explicit position control. This approach balances simplicity, performance, and customization.
Categories (y-axis)
┌─────────────────────────────┐
│  ┌─────┐  ┌──────┐  ┌───┐   │
│  │Bar1 │  │Bar2  │  │Bar3│   │
│  └─────┘  └──────┘  └───┘   │
│  Positions shifted vertically│
│  Bars drawn as rectangles    │
└─────────────────────────────┘
Values control bar width (x-axis)
Myth Busters - 4 Common Misconceptions
Quick: Do horizontal grouped bars require bars to be stacked vertically? Commit to yes or no.
Common Belief:Grouped bars must be stacked on top of each other vertically to show groups.
Tap to reveal reality
Reality:Grouped bars are placed side by side horizontally by shifting their vertical positions, not stacked on top.
Why it matters:Stacking bars instead of grouping side by side changes the visual meaning and can confuse comparisons between groups.
Quick: Do you think bar height controls the length of the bar in horizontal bar charts? Commit to yes or no.
Common Belief:Bar height controls how long the bar is in horizontal bar charts.
Tap to reveal reality
Reality:Bar height controls the thickness of the bar; the length is controlled by the value plotted along the x-axis.
Why it matters:Misunderstanding this leads to incorrect bar sizing and misleading visualizations.
Quick: Can you group bars horizontally without adjusting their y-axis positions? Commit to yes or no.
Common Belief:Bars automatically group horizontally without manual position adjustments.
Tap to reveal reality
Reality:You must manually shift bars' y-axis positions to create horizontal groups; matplotlib does not auto-group them.
Why it matters:Assuming automatic grouping causes overlapping bars and unreadable charts.
Quick: Do you think horizontal grouped bars are less readable than vertical ones? Commit to yes or no.
Common Belief:Horizontal grouped bars are harder to read than vertical grouped bars.
Tap to reveal reality
Reality:Horizontal grouped bars are often more readable, especially when category labels are long or numerous.
Why it matters:Choosing vertical bars by default may reduce clarity when horizontal grouping is better suited.
Expert Zone
1
Precise control of bar height and spacing is crucial to avoid visual clutter or overlap, especially with many groups.
2
When groups have uneven numbers of bars, dynamic calculation of positions prevents misalignment and maintains readability.
3
Using alpha transparency and hatch patterns can help distinguish groups when color palettes are limited or for colorblind accessibility.
When NOT to use
Avoid horizontal grouped bars when you have too many groups or sub-categories, as the chart becomes cluttered and hard to read. Instead, consider interactive plots, small multiples, or summary statistics. Also, if the focus is on total composition rather than comparison, stacked bars or pie charts might be better.
Production Patterns
Professionals use horizontal grouped bars in dashboards to compare sales across regions and product lines, in reports to show survey results by demographic groups, and in presentations to highlight performance differences. They often combine these charts with annotations, tooltips, and consistent color schemes for clarity.
Connections
Stacked bar charts
Alternative way to show multiple sub-categories within categories by stacking bars vertically instead of grouping side by side.
Understanding grouped bars clarifies when stacking is better for showing part-to-whole relationships versus side-by-side comparison.
Data visualization principles
Horizontal grouped bars apply core principles like pre-attentive processing and spatial grouping to improve data comprehension.
Knowing visualization principles helps design grouped bars that communicate data clearly and avoid misleading impressions.
Music notation (different instruments in a score)
Like grouped bars, music scores group different instruments' notes horizontally aligned by time, allowing simultaneous comparison.
Recognizing grouping patterns across fields shows how arranging related elements side by side aids understanding complex information.
Common Pitfalls
#1Bars overlap because positions are not shifted correctly.
Wrong approach:plt.barh(indices, values1, height=0.4) plt.barh(indices, values2, height=0.4)
Correct approach:plt.barh(indices - 0.2, values1, height=0.4) plt.barh(indices + 0.2, values2, height=0.4)
Root cause:Not offsetting y-axis positions causes bars to draw on top of each other.
#2Using the same color for all groups, causing confusion.
Wrong approach:plt.barh(indices - 0.2, values1, height=0.4, color='blue') plt.barh(indices + 0.2, values2, height=0.4, color='blue')
Correct approach:plt.barh(indices - 0.2, values1, height=0.4, color='blue') plt.barh(indices + 0.2, values2, height=0.4, color='orange')
Root cause:Not differentiating groups visually makes it hard to distinguish bars.
#3Placing y-ticks incorrectly, misaligning labels with bars.
Wrong approach:plt.yticks(indices + 0.2, categories)
Correct approach:plt.yticks(indices, categories)
Root cause:Misunderstanding that y-ticks should align with the center of grouped bars, not shifted positions.
Key Takeaways
Horizontal grouped bars display multiple sub-categories side by side along the horizontal axis for clear comparison.
Shifting bar positions vertically is essential to create distinct groups and avoid overlap.
Colors, labels, and legends improve readability and help viewers quickly identify groups.
Handling uneven group sizes requires dynamic positioning to maintain clarity.
Understanding the internal mechanics of bar placement helps avoid common mistakes and design effective visualizations.

Practice

(1/5)
1.

What is the main purpose of using horizontal grouped bars in a chart?

easy
A. To compare multiple categories side by side horizontally
B. To show data as a pie chart
C. To display data only vertically
D. To create a line graph

Solution

  1. Step 1: Understand the chart type

    Horizontal grouped bars place bars side by side horizontally to compare groups.
  2. Step 2: Identify the purpose

    This layout helps compare multiple categories clearly across groups.
  3. Final Answer:

    To compare multiple categories side by side horizontally -> Option A
  4. Quick Check:

    Horizontal grouped bars = compare categories horizontally [OK]
Hint: Grouped bars show side-by-side comparisons horizontally [OK]
Common Mistakes:
  • Confusing horizontal bars with pie charts
  • Thinking grouped bars are vertical only
  • Mixing line graphs with bar charts
2.

Which of the following is the correct way to create horizontal grouped bars in matplotlib?

import matplotlib.pyplot as plt
import numpy as np

labels = ['A', 'B', 'C']
values1 = [5, 7, 3]
values2 = [6, 2, 4]

x = np.arange(len(labels))
width = 0.35

plt.barh(x, values1, height=width)
plt.barh(x + width, values2, height=width)
plt.show()
easy
A. Use plt.scatter for grouped bars
B. Use plt.bar with shifted positions for each group
C. Use plt.plot with x and y values
D. Use plt.barh with shifted positions for each group

Solution

  1. Step 1: Check the function used

    The code uses plt.barh which creates horizontal bars.
  2. Step 2: Verify grouping method

    Positions are shifted by adding width to x to group bars side by side horizontally.
  3. Final Answer:

    Use plt.barh with shifted positions for each group -> Option D
  4. Quick Check:

    plt.barh + shifted positions = grouped horizontal bars [OK]
Hint: Use plt.barh and shift positions to group bars horizontally [OK]
Common Mistakes:
  • Using plt.bar instead of plt.barh for horizontal bars
  • Not shifting positions causing overlapping bars
  • Using plt.plot or plt.scatter which are not bar charts
3.

What will be the output of the following code?

import matplotlib.pyplot as plt
import numpy as np

labels = ['X', 'Y']
values1 = [3, 8]
values2 = [5, 2]

x = np.arange(len(labels))
width = 0.4

plt.barh(x, values1, height=width, color='blue')
plt.barh(x + width, values2, height=width, color='red')
plt.yticks(x + width / 2, labels)
plt.show()
medium
A. A line plot with two lines
B. Two vertical bar groups overlapping
C. Two sets of horizontal bars side by side for each label
D. A scatter plot with points at x positions

Solution

  1. Step 1: Analyze barh usage

    plt.barh creates horizontal bars at positions x and x + width, shifted to group bars.
  2. Step 2: Check y-axis labels

    yticks are set at middle positions between bars for labels 'X' and 'Y'.
  3. Final Answer:

    Two sets of horizontal bars side by side for each label -> Option C
  4. Quick Check:

    barh + shifted positions + ytick labels = grouped horizontal bars [OK]
Hint: Shift y positions and set yticks for grouped horizontal bars [OK]
Common Mistakes:
  • Confusing horizontal bars with vertical bars
  • Not setting yticks causing label misalignment
  • Expecting line or scatter plot output
4.

Identify the error in this code for horizontal grouped bars:

import matplotlib.pyplot as plt
import numpy as np

labels = ['P', 'Q', 'R']
values1 = [4, 6, 5]
values2 = [7, 3, 8]

x = np.arange(len(labels))
width = 0.3

plt.barh(x, values1, height=width)
plt.barh(x, values2, height=width)
plt.yticks(x + width / 2, labels)
plt.show()
medium
A. Bars overlap because positions are not shifted for grouping
B. Height parameter is missing
C. yticks are set incorrectly
D. Values lists have different lengths

Solution

  1. Step 1: Check bar positions

    Both plt.barh calls use the same x positions, so bars overlap instead of grouping.
  2. Step 2: Verify grouping method

    Positions should be shifted by width to separate groups horizontally.
  3. Final Answer:

    Bars overlap because positions are not shifted for grouping -> Option A
  4. Quick Check:

    Same x positions without shift = overlapping bars [OK]
Hint: Shift bar positions to avoid overlap in grouped bars [OK]
Common Mistakes:
  • Not shifting positions for second group
  • Incorrect yticks placement
  • Assuming height parameter fixes overlap
5.

You have sales data for 3 products over 2 years:

products = ['A', 'B', 'C']
year1 = [10, 15, 7]
year2 = [12, 9, 14]

How would you create a horizontal grouped bar chart to compare sales by product and year, ensuring product labels appear centered between grouped bars?

hard
A. Use plt.plot to draw lines for each product
B. Use plt.barh with positions shifted by width and set yticks at x + width/2
C. Use plt.barh with same positions for both years and set yticks at x
D. Use plt.bar with positions shifted by width and set xticks at x + width/2

Solution

  1. Step 1: Use plt.barh with shifted positions

    Shift positions by width for each year to group bars horizontally side by side.
  2. Step 2: Set yticks at middle of grouped bars

    Set yticks at x + width/2 so product labels appear centered between bars.
  3. Final Answer:

    Use plt.barh with positions shifted by width and set yticks at x + width/2 -> Option B
  4. Quick Check:

    Shift positions + yticks center = clear grouped horizontal bars [OK]
Hint: Shift bars and center yticks for clear grouped horizontal bars [OK]
Common Mistakes:
  • Using vertical bars instead of horizontal
  • Not shifting positions causing overlap
  • Setting yticks incorrectly causing label misalignment
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard