Bird
Raised Fist0
Matplotlibdata~10 mins

Grouped bar charts in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Grouped bar charts
Prepare data for groups and categories
↓
Calculate bar positions for each group
↓
Plot bars side-by-side for each category
↓
Add labels, title, legend
↓
Display the grouped bar chart
Grouped bar charts show multiple bars side-by-side for each group, allowing easy comparison across categories.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt

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

x = range(len(labels))

plt.bar([p - 0.2 for p in x], values1, width=0.4, label='Set 1')
plt.bar([p + 0.2 for p in x], values2, width=0.4, label='Set 2')

plt.xticks(x, labels)
plt.legend()
plt.show()
This code plots two sets of bars side-by-side for each label, creating a grouped bar chart.
Execution Table
StepActionVariable/ValueEffect/Output
1Define labelslabels = ['A', 'B', 'C']Labels for x-axis groups set
2Define values1values1 = [5, 7, 3]First data set values stored
3Define values2values2 = [6, 8, 4]Second data set values stored
4Calculate x positionsx = range(3)x = [0,1,2], positions for groups
5Calculate positions for bars set 1[p - 0.2 for p in x]Positions: [-0.2, 0.8, 1.8] for first bars
6Plot bars set 1plt.bar([p - 0.2 for p in x], values1, width=0.4, label='Set 1')Bars for Set 1 drawn at shifted left positions
7Calculate positions for bars set 2[p + 0.2 for p in x]Positions: [0.2, 1.2, 2.2] for second bars
8Plot bars set 2plt.bar([p + 0.2 for p in x], values2, width=0.4, label='Set 2')Bars for Set 2 drawn at shifted right positions
9Set x-axis ticksplt.xticks(x, labels)Labels 'A','B','C' shown under groups
10Add legendplt.legend()Legend shows 'Set 1' and 'Set 2' labels
11Show plotplt.show()Grouped bar chart displayed
12End-Execution complete
💡 All bars plotted and chart displayed, execution ends.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 7Final
labelsundefined['A', 'B', 'C']['A', 'B', 'C']['A', 'B', 'C']['A', 'B', 'C']
values1undefined[5, 7, 3][5, 7, 3][5, 7, 3][5, 7, 3]
values2undefined[6, 8, 4][6, 8, 4][6, 8, 4][6, 8, 4]
xundefined[0, 1, 2][0, 1, 2][0, 1, 2][0, 1, 2]
positions set 1undefinedundefined[-0.2, 0.8, 1.8][-0.2, 0.8, 1.8][-0.2, 0.8, 1.8]
positions set 2undefinedundefinedundefined[0.2, 1.2, 2.2][0.2, 1.2, 2.2]
Key Moments - 3 Insights
Why do we subtract and add 0.2 to the x positions for the two sets of bars?
Subtracting 0.2 shifts the first set of bars slightly left, and adding 0.2 shifts the second set right, so bars don't overlap and appear side-by-side as shown in steps 5 and 7.
What does plt.xticks(x, labels) do in the grouped bar chart?
It sets the x-axis ticks at positions x = [0,1,2] and labels them with 'A', 'B', 'C' so viewers know which group each pair of bars belongs to, as in step 9.
Why do we use the same width (0.4) for both sets of bars?
Using the same width ensures bars are uniform in size and fit neatly side-by-side without overlapping, as seen in steps 6 and 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 5. What are the positions for the first set of bars?
A[-0.2, 0.8, 1.8]
B[0, 1, 2]
C[0.2, 1.2, 2.2]
D[0.4, 1.4, 2.4]
💡 Hint
Check the 'Variable/Value' column at step 5 in the execution_table.
At which step are the x-axis labels 'A', 'B', 'C' set under the bars?
AStep 6
BStep 7
CStep 9
DStep 10
💡 Hint
Look for plt.xticks call in the execution_table.
If we increase the bar width to 0.8 for both sets, what will likely happen?
ABars will disappear
BBars will overlap because total width exceeds group spacing
CBars will be thinner and spaced out
DBars will be colored differently
💡 Hint
Consider the width and position shifts in steps 5, 6, 7, and 8.
Concept Snapshot
Grouped bar charts show multiple bars side-by-side for each group.
Use position shifts (e.g., -0.2, +0.2) to separate bars.
Set bar width to fit bars neatly without overlap.
Use plt.xticks to label groups on x-axis.
Add legend to identify each data set.
Call plt.show() to display the chart.
Full Transcript
This visual execution traces how to create grouped bar charts using matplotlib. We start by defining labels and two sets of values. We calculate x positions for groups and shift them left and right to place bars side-by-side. Bars are plotted with the same width to avoid overlap. The x-axis ticks are set to show group labels, and a legend is added to distinguish data sets. Finally, the chart is displayed. Key points include shifting bar positions to group them and setting x-axis labels for clarity.

Practice

(1/5)
1. What is the main purpose of a grouped bar chart in data visualization?
easy
A. To compare multiple categories side by side within groups
B. To show the trend of a single variable over time
C. To display parts of a whole as percentages
D. To plot data points on a continuous scale

Solution

  1. Step 1: Understand the chart type

    Grouped bar charts place bars for different categories next to each other for easy comparison.
  2. Step 2: Identify the purpose

    This helps compare multiple categories side by side within groups, unlike line or pie charts.
  3. Final Answer:

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

    Grouped bars = side-by-side comparison [OK]
Hint: Grouped bars show categories side by side for easy comparison [OK]
Common Mistakes:
  • Confusing grouped bar charts with line charts
  • Thinking grouped bars show parts of a whole
  • Assuming grouped bars plot continuous data
2. Which of the following code snippets correctly shifts bars to create a grouped bar chart in matplotlib?
easy
A. plt.bar(x - width/2, data1, width); plt.bar(x + width/2, data2, width)
B. plt.bar(x, data1, width); plt.bar(x, data2, width)
C. plt.bar(x + width, data1, width); plt.bar(x + width, data2, width)
D. plt.bar(x - width, data1, width); plt.bar(x - width, data2, width)

Solution

  1. Step 1: Understand bar shifting for grouping

    To group bars side by side, shift one set left by half the bar width and the other right by half the bar width.
  2. Step 2: Check the code

    plt.bar(x - width/2, data1, width); plt.bar(x + width/2, data2, width) shifts bars by -width/2 and +width/2, correctly grouping them.
  3. Final Answer:

    plt.bar(x - width/2, data1, width); plt.bar(x + width/2, data2, width) -> Option A
  4. Quick Check:

    Shift bars ±width/2 for grouping [OK]
Hint: Shift bars by ±width/2 to group them side by side [OK]
Common Mistakes:
  • Not shifting bars, causing overlap
  • Shifting bars by full width, creating gaps
  • Using the same x positions for all bars
3. What will be the output of the following code?
import matplotlib.pyplot as plt
import numpy as np

labels = ['A', 'B', 'C']
data1 = [5, 7, 9]
data2 = [6, 8, 10]
x = np.arange(len(labels))
width = 0.4

plt.bar(x - width/2, data1, width, label='Data1')
plt.bar(x + width/2, data2, width, label='Data2')
plt.xticks(x, labels)
plt.legend()
plt.show()
medium
A. A stacked bar chart with Data2 bars on top of Data1 bars
B. A grouped bar chart with bars for Data1 and Data2 side by side for each label
C. A line chart connecting data points for Data1 and Data2
D. A scatter plot with points at positions x and data values

Solution

  1. Step 1: Analyze the bar positions

    Bars for data1 are at x - width/2, and for data2 at x + width/2, placing them side by side.
  2. Step 2: Understand the plot type

    Using plt.bar twice with shifted x positions creates a grouped bar chart, not stacked or line chart.
  3. Final Answer:

    A grouped bar chart with bars for Data1 and Data2 side by side for each label -> Option B
  4. Quick Check:

    Shifted bars = grouped bar chart [OK]
Hint: Shift bars left and right to get grouped bars, not stacked [OK]
Common Mistakes:
  • Thinking bars are stacked instead of grouped
  • Confusing bar chart with line or scatter plot
  • Ignoring the x-axis label positions
4. Identify the error in this grouped bar chart code:
import matplotlib.pyplot as plt
import numpy as np

labels = ['X', 'Y', 'Z']
data1 = [3, 5, 7]
data2 = [4, 6, 8]
x = np.arange(len(labels))
width = 0.3

plt.bar(x, data1, width, label='Data1')
plt.bar(x + width/2, data2, width, label='Data2')
plt.xticks(x, labels)
plt.legend()
plt.show()
medium
A. Legend labels are missing
B. Width is too large causing bars to be invisible
C. x positions are incorrect and cause an error
D. Bars overlap because data1 bars are not shifted left

Solution

  1. Step 1: Check bar positions

    data1 bars are at x, data2 bars at x + width/2, so data1 bars are not shifted left to avoid overlap.
  2. Step 2: Understand grouping logic

    To group bars, data1 should be at x - width/2 and data2 at x + width/2; otherwise, bars overlap.
  3. Final Answer:

    Bars overlap because data1 bars are not shifted left -> Option D
  4. Quick Check:

    Shift both bars ±width/2 to avoid overlap [OK]
Hint: Shift first bars left by width/2 to prevent overlap [OK]
Common Mistakes:
  • Not shifting first bar set left
  • Using full width shift causing gaps
  • Ignoring bar width when setting positions
5. You have sales data for 3 products over 4 quarters:
products = ['P1', 'P2', 'P3']
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
sales = [[10, 15, 20, 25], [12, 18, 22, 28], [14, 20, 24, 30]]
How would you create a grouped bar chart showing sales per quarter for each product using matplotlib?
hard
A. Use a line plot instead of bars for grouped comparison
B. Plot bars at x positions equal to product indices without shifting
C. Use x = np.arange(len(quarters)), width = 0.25, then plot bars for each product shifted by -width, 0, +width
D. Stack bars for all products at the same x positions for quarters

Solution

  1. Step 1: Set x positions for quarters

    Use x = np.arange(len(quarters)) to represent each quarter on the x-axis.
  2. Step 2: Define bar width and shifts

    Set width = 0.25 and shift bars for each product by -width, 0, and +width to group them side by side.
  3. Step 3: Plot bars for each product

    Plot bars for each product's sales data at shifted x positions to create grouped bars per quarter.
  4. Final Answer:

    Use x = np.arange(len(quarters)), width = 0.25, then plot bars for each product shifted by -width, 0, +width -> Option C
  5. Quick Check:

    Shift bars by ±width around x for grouping [OK]
Hint: Shift bars by ±width around x for each product group [OK]
Common Mistakes:
  • Not shifting bars causing overlap
  • Using product indices as x instead of quarters
  • Stacking bars instead of grouping
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