Basic plt.plot usage in Matplotlib - Time & Space Complexity
We want to understand how the time to draw a simple line plot changes as we add more points.
How does the work grow when we plot more data?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
n = 10 # Example value for n
x = list(range(n))
y = [i * 2 for i in x]
plt.plot(x, y)
plt.show()
This code creates two lists of length n and plots them as a line chart.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating the lists x and y by going through n elements.
- How many times: Each list is built by repeating an operation n times.
- Plotting: The plot function processes all n points once to draw the line.
As n grows, the number of operations grows roughly the same as n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations to build lists and plot |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: Doubling the number of points roughly doubles the work.
Time Complexity: O(n)
This means the time to plot grows linearly with the number of points.
[X] Wrong: "Plotting a line is always constant time no matter how many points."
[OK] Correct: The plot must process each point to draw the line, so more points mean more work.
Understanding how plotting time grows helps you reason about performance when working with large datasets.
"What if we plotted multiple lines instead of one? How would the time complexity change?"