Basic scatter plot with plt.scatter in Matplotlib - Time & Space Complexity
We want to understand how the time to create a scatter plot changes as we add more points.
How does the number of points affect the work matplotlib does?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
n = 100 # example value for n
x = range(n)
y = range(n)
plt.scatter(x, y)
plt.show()
This code creates a scatter plot with n points, plotting each (x, y) pair.
- Primary operation: Plotting each point on the scatter plot.
- How many times: Once for each of the n points.
As we add more points, the work grows directly with the number of points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: Doubling the points roughly doubles the work.
Time Complexity: O(n)
This means the time to draw the scatter plot grows linearly with the number of points.
[X] Wrong: "Adding more points won't affect the time much because plotting is fast."
[OK] Correct: Each point requires work to draw, so more points mean more time.
Understanding how plotting time grows helps you explain performance when working with large datasets.
"What if we used plt.scatter with multiple calls each plotting a small group of points? How would the time complexity change?"