Overlaying data on images in Matplotlib - Time & Space Complexity
When we overlay data on images using matplotlib, we want to know how the time to draw changes as the data grows.
How does adding more points or lines affect the drawing time?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
img = np.random.rand(100, 100)
plt.imshow(img, cmap='gray')
x = np.arange(0, 100)
y = np.sin(x / 10) * 50 + 50
plt.plot(x, y, color='red')
plt.show()
This code shows a 100x100 image and overlays a red sine wave line on top.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing each point of the line over the image.
- How many times: Once for each x value, here 100 times.
As the number of points in the line increases, the drawing time grows roughly in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 drawing steps |
| 100 | 100 drawing steps |
| 1000 | 1000 drawing steps |
Pattern observation: Doubling the number of points roughly doubles the work needed to draw the overlay.
Time Complexity: O(n)
This means the time to overlay data grows linearly with the number of points you draw.
[X] Wrong: "Overlaying data on an image takes constant time no matter how many points are drawn."
[OK] Correct: Each point or line segment must be drawn separately, so more points mean more drawing steps and more time.
Understanding how drawing time grows helps you write efficient visualization code and explain performance in real projects.
What if we changed the overlay from a line plot to a scatter plot with thousands of points? How would the time complexity change?