Horizontal grouped bars in Matplotlib - Time & Space Complexity
We want to understand how the time to draw horizontal grouped bars changes as we add more groups or bars.
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
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 - width/2, values1, height=width, label='Group 1')
plt.barh(x + width/2, values2, height=width, label='Group 2')
plt.yticks(x, labels)
plt.legend()
plt.show()
This code draws two horizontal bars side by side for each label, grouping them visually.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing bars for each group and label combination.
- How many times: For each label, bars are drawn for each group, so total bars = number of labels x number of groups.
As the number of labels or groups increases, the number of bars to draw grows proportionally.
| Input Size (labels x groups) | Approx. Operations (bars drawn) |
|---|---|
| 10 labels x 2 groups = 20 | 20 bars |
| 100 labels x 2 groups = 200 | 200 bars |
| 1000 labels x 2 groups = 2000 | 2000 bars |
Pattern observation: The drawing time grows linearly with the total number of bars.
Time Complexity: O(n * g)
This means the time grows in direct proportion to the number of labels (n) times the number of groups (g).
[X] Wrong: "Adding more groups does not affect drawing time much because bars are drawn together."
[OK] Correct: Each group adds a full set of bars for every label, so total bars increase and so does drawing time.
Understanding how drawing time scales helps you explain performance when visualizing large datasets with grouped bars.
What if we changed from grouped bars to stacked bars? How would the time complexity change?