Diverging bar charts in Matplotlib - Time & Space Complexity
We want to understand how the time to create a diverging bar chart changes as the data size grows.
How does the number of bars affect the work matplotlib does?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
values = np.random.randn(100) # 100 data points
colors = ['green' if x >= 0 else 'red' for x in values]
plt.bar(range(len(values)), values, color=colors)
plt.show()
This code creates a diverging bar chart with 100 bars colored by positive or negative values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing each bar in the chart.
- How many times: Once for each data point (here, 100 times).
As the number of bars increases, the work to draw them grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 drawing operations |
| 100 | 100 drawing operations |
| 1000 | 1000 drawing operations |
Pattern observation: Doubling the number of bars roughly doubles the work.
Time Complexity: O(n)
This means the time to draw the chart grows linearly with the number of bars.
[X] Wrong: "Adding more bars won't affect the drawing time much because the chart size stays the same."
[OK] Correct: Each bar requires separate drawing work, so more bars mean more work even if the chart area is fixed.
Understanding how drawing operations scale helps you explain performance in data visualization tasks clearly and confidently.
"What if we added nested loops to draw multiple diverging bar charts in a grid? How would the time complexity change?"