NumPy with Matplotlib - Time & Space Complexity
We want to understand how the time needed to run NumPy and Matplotlib code changes as the data size grows.
Specifically, how does plotting data from NumPy arrays affect execution time?
Analyze the time complexity of the following code snippet.
import numpy as np
import matplotlib.pyplot as plt
n = 1000
x = np.linspace(0, 10, n)
y = np.sin(x)
plt.plot(x, y)
plt.show()
This code creates an array of n points, computes their sine values, and plots them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Computing sine for each of the n points in the array.
- How many times: Once for each of the n elements.
As n grows, the number of sine calculations and points to plot grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 sine calculations and 10 plot points |
| 100 | About 100 sine calculations and 100 plot points |
| 1000 | About 1000 sine calculations and 1000 plot points |
Pattern observation: Doubling n roughly doubles the work done.
Time Complexity: O(n)
This means the time to compute and plot grows directly with the number of points.
[X] Wrong: "Plotting always takes constant time regardless of data size."
[OK] Correct: Plotting needs to process each data point, so more points mean more work and longer time.
Understanding how data size affects plotting time helps you explain performance in data visualization tasks clearly and confidently.
"What if we used a scatter plot instead of a line plot? How would the time complexity change?"