Grouped bar charts in Matplotlib - Time & Space Complexity
When we create grouped bar charts with matplotlib, we want to know how the time to draw the chart changes as we add more groups or bars.
We ask: How does the drawing time grow when the data size grows?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D']
values1 = [5, 7, 3, 4]
values2 = [6, 8, 4, 5]
x = range(len(labels))
width = 0.35
plt.bar([i - width/2 for i in x], values1, width=width, label='Group 1')
plt.bar([i + width/2 for i in x], values2, width=width, label='Group 2')
plt.legend()
plt.show()
This code draws two groups of bars side by side for each label.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing bars for each group and label.
- How many times: Once per bar, so number of groups times number of labels.
As the number of labels or groups grows, the number of bars to draw grows too.
| Input Size (n = labels x groups) | Approx. Operations |
|---|---|
| 10 (e.g., 5 labels x 2 groups) | About 10 bar draws |
| 100 (e.g., 50 labels x 2 groups) | About 100 bar draws |
| 1000 (e.g., 500 labels x 2 groups) | About 1000 bar draws |
Pattern observation: The drawing work grows directly with the total number of bars.
Time Complexity: O(n)
This means the time to draw grows in a straight line with the number of bars.
[X] Wrong: "Adding more groups does not affect drawing time much because bars are drawn together."
[OK] Correct: Each bar is drawn separately, so more groups mean more bars and more drawing steps.
Understanding how drawing time grows helps you explain performance when visualizing large datasets, a useful skill in data science roles.
"What if we added a third group of bars? How would the time complexity change?"