Annotation with arrows in Matplotlib - Time & Space Complexity
We want to understand how the time to add annotations with arrows changes as we add more points.
How does the work grow when we add more arrows to a plot?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
points = [(1, 2), (2, 3), (3, 5), (4, 7)]
for x, y in points:
ax.plot(x, y, 'bo')
ax.annotate('Point', xy=(x, y), xytext=(x+0.1, y+0.1), arrowprops=dict(arrowstyle='->'))
plt.show()
This code plots points and adds an arrow annotation for each point.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each point to add a plot and an annotation with an arrow.
- How many times: Once for each point in the list.
Each new point adds one more arrow annotation, so the work grows steadily with the number of points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 plot points + 10 annotations |
| 100 | 100 plot points + 100 annotations |
| 1000 | 1000 plot points + 1000 annotations |
Pattern observation: The total work increases directly with the number of points.
Time Complexity: O(n)
This means the time to add annotations with arrows grows in a straight line as you add more points.
[X] Wrong: "Adding arrows is a fixed cost no matter how many points there are."
[OK] Correct: Each arrow requires drawing and positioning, so more points mean more work.
Knowing how adding annotations scales helps you understand performance when visualizing large datasets.
"What if we added nested loops to annotate pairs of points with arrows? How would the time complexity change?"