Vertical bar chart with plt.bar in Matplotlib - Time & Space Complexity
When we create a vertical bar chart using plt.bar, the time it takes depends on how many bars we draw.
We want to know how the work grows as we add more bars.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C', 'D', 'E']
values = [5, 7, 3, 8, 4]
plt.bar(categories, values)
plt.show()
This code draws a vertical bar chart with 5 bars, one for each category.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing each bar on the chart.
- How many times: Once for each category in the list.
As the number of bars increases, the time to draw grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 drawing steps |
| 100 | 100 drawing steps |
| 1000 | 1000 drawing steps |
Pattern observation: Doubling the bars doubles the work.
Time Complexity: O(n)
This means the time to draw the chart grows directly with the number of bars.
[X] Wrong: "Adding more bars won't affect drawing time much because it's just one command."
[OK] Correct: Each bar is drawn separately, so more bars mean more drawing steps and more time.
Understanding how drawing time grows helps you explain performance when working with charts and visualizations in real projects.
"What if we added error bars to each bar? How would the time complexity change?"