Annotating specific points in Matplotlib - Time & Space Complexity
When we add annotations to specific points in a plot, it takes some extra work for the computer. We want to understand how this extra work grows as we add more points to annotate.
The question is: How does the time needed to add annotations change when we increase the number of points?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i in range(len(x)):
plt.annotate(f"({x[i]}, {y[i]})", (x[i], y[i]))
plt.show()
This code plots points and adds a text label next to each point showing its coordinates.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that adds an annotation for each point.
- How many times: Once for each point in the data (n times).
Each point gets one annotation, so the work grows directly with the number of points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 annotations |
| 100 | 100 annotations |
| 1000 | 1000 annotations |
Pattern observation: Doubling the points doubles the annotation work.
Time Complexity: O(n)
This means the time to add annotations grows in a straight line with the number of points.
[X] Wrong: "Adding annotations is instant and does not depend on how many points there are."
[OK] Correct: Each annotation requires extra drawing work, so more points mean more annotations and more time.
Understanding how adding features like annotations affects performance helps you write better, more efficient code in real projects.
"What if we only annotate every 10th point instead of every point? How would the time complexity change?"