Horizontal bar chart with plt.barh in Matplotlib - Time & Space Complexity
We want to understand how the time to draw a horizontal bar chart changes as we add more bars.
How does the work grow when the number of bars increases?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D', 'E']
values = [5, 7, 3, 8, 4]
plt.barh(labels, values)
plt.show()
This code draws a horizontal bar chart with 5 bars labeled A to E with given values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing each bar on the chart.
- How many times: Once for each label and value pair (here 5 times).
As the number of bars increases, the drawing work grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 drawing steps |
| 100 | 100 drawing steps |
| 1000 | 1000 drawing steps |
Pattern observation: Doubling the bars doubles the drawing work.
Time Complexity: O(n)
This means the time to draw the chart grows directly with the number of bars.
[X] Wrong: "Drawing a bar chart takes the same time no matter how many bars there are."
[OK] Correct: Each bar needs to be drawn separately, so more bars mean more work.
Understanding how drawing time grows helps you explain performance when visualizing data with many points.
What if we added nested loops to draw grouped bars? How would the time complexity change?