Saving figures in Data Analysis Python - Time & Space Complexity
When saving figures in data analysis, we want to know how the time needed changes as the figure size or data grows.
We ask: How does saving time grow when the figure gets more complex or larger?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 1000)
y = np.sin(x)
plt.plot(x, y)
plt.savefig('figure.png')
plt.close()
This code creates a line plot with 1000 points and saves it as an image file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Plotting the 1000 points and writing the image file.
- How many times: The plotting processes each of the 1000 points once; saving writes the whole image once.
As the number of points increases, the time to plot and save grows roughly in proportion.
| Input Size (n points) | Approx. Operations |
|---|---|
| 10 | Low, quick plot and save |
| 100 | About 10 times more work than 10 points |
| 1000 | About 100 times more work than 10 points |
Pattern observation: The time grows roughly linearly with the number of points plotted and saved.
Time Complexity: O(n)
This means the time to save the figure grows in a straight line as the number of points increases.
[X] Wrong: "Saving a figure always takes the same time no matter how big it is."
[OK] Correct: Larger figures with more data points take longer to process and save because more information must be handled.
Understanding how saving figures scales helps you explain performance in data projects and shows you can think about efficiency in real tasks.
"What if we save the figure in a different format like SVG instead of PNG? How would the time complexity change?"