0
0
Matplotlibdata~20 mins

Bar width and positioning in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Bar Chart Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
Bar chart with custom bar width
What is the width of each bar in the resulting bar chart from this code?
Matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3]
heights = [4, 5, 6]
plt.bar(x, heights, width=0.5)
plt.show()
A0.8
B0.3
C1.0
D0.5
Attempts:
2 left
💡 Hint
Look at the width parameter in plt.bar function.
data_output
intermediate
2:00remaining
Positions of grouped bars
Given two groups of bars plotted side by side with width 0.4, what are the x positions of the bars in the second group?
Matplotlib
import numpy as np
import matplotlib.pyplot as plt

labels = ['A', 'B', 'C']
x = np.arange(len(labels))
width = 0.4

plt.bar(x - width/2, [1, 2, 3], width=width)
plt.bar(x + width/2, [4, 5, 6], width=width)
plt.show()

positions_second_group = x + width/2
print(positions_second_group)
A[0.2 1.2 2.2]
B[-0.2 0.8 1.8]
C[0.4 1.4 2.4]
D[0.0 1.0 2.0]
Attempts:
2 left
💡 Hint
Positions are shifted by half the bar width to the right for the second group.
visualization
advanced
2:00remaining
Effect of bar width on bar overlap
Which bar width will cause the bars to overlap when plotted at positions [0, 1, 2]?
Matplotlib
import matplotlib.pyplot as plt

x = [0, 1, 2]
heights = [3, 4, 5]

plt.bar(x, heights, width=1.2)
plt.show()
A0.5
B0.8
C1.2
D1.0
Attempts:
2 left
💡 Hint
Bars overlap if width is greater than the distance between bar centers.
🧠 Conceptual
advanced
1:30remaining
Understanding bar alignment parameter
What does setting the 'align' parameter to 'edge' do in plt.bar compared to the default 'center'?
ABars are aligned so their left edges are at the x positions instead of centers.
BBars are aligned so their centers are at the x positions (default behavior).
CBars are aligned so their right edges are at the x positions.
DBars are stacked vertically instead of side by side.
Attempts:
2 left
💡 Hint
Think about where the bar starts relative to the x coordinate.
🔧 Debug
expert
2:30remaining
Fixing incorrect bar positions in grouped bar chart
Given this code, which option correctly fixes the bar positions so the two groups do not overlap?
Matplotlib
import numpy as np
import matplotlib.pyplot as plt

labels = ['X', 'Y', 'Z']
x = np.arange(len(labels))
width = 0.3

plt.bar(x, [5, 7, 9], width=width)
plt.bar(x, [6, 8, 10], width=width)
plt.show()
AChange second plt.bar to plt.bar(x + width, [6, 8, 10], width=width)
BChange first plt.bar to plt.bar(x - width/2, [5, 7, 9], width=width) and second to plt.bar(x + width/2, [6, 8, 10], width=width)
CChange second plt.bar to plt.bar(x - width, [6, 8, 10], width=width)
DChange width to 0.6 for both bars
Attempts:
2 left
💡 Hint
To avoid overlap, shift bars left and right by half the width.