Axis limits (xlim, ylim) in Matplotlib - Time & Space Complexity
We want to understand how setting axis limits affects the time it takes to draw a plot.
Specifically, does changing limits make the drawing slower as data grows?
Analyze the time complexity of this matplotlib code snippet.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 100, 1000)
y = np.sin(x)
plt.plot(x, y)
plt.xlim(20, 80)
plt.ylim(-0.5, 0.5)
plt.show()
This code plots a sine wave and sets the x and y axis limits to zoom in on a part of the data.
Look for loops or repeated steps in drawing and setting limits.
- Primary operation: Drawing 1000 points on the plot.
- How many times: Once for each point in the data arrays.
The time to draw grows as the number of points increases, but setting axis limits is a simple step.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 drawing steps + 1 limit setting |
| 100 | About 100 drawing steps + 1 limit setting |
| 1000 | About 1000 drawing steps + 1 limit setting |
Pattern observation: Drawing time grows with data size, but setting limits stays constant.
Time Complexity: O(n)
This means the time to draw grows linearly with the number of points, while setting axis limits adds a fixed small cost.
[X] Wrong: "Setting axis limits slows down the plot a lot as data grows."
[OK] Correct: Setting limits is a simple step done once, so it does not grow with data size.
Understanding how plotting steps scale helps you explain performance in data visualization tasks clearly and confidently.
What if we added a loop to set axis limits multiple times? How would the time complexity change?