Axes vs pyplot interface comparison in Matplotlib - Performance Comparison
We want to see how the time it takes to create plots changes when using different matplotlib interfaces.
Which interface grows faster in time as we add more plots?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
n = len(data)
fig, axs = plt.subplots(nrows=1, ncols=n)
for i in range(n):
axs[i].plot(data[i])
plt.show()
This code creates a figure with n subplots using the Axes interface and plots data on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over
naxes to plot data. - How many times: Exactly
ntimes, once per subplot.
As the number of subplots n increases, the plotting work grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 plot calls |
| 100 | 100 plot calls |
| 1000 | 1000 plot calls |
Pattern observation: Doubling n doubles the number of plot operations.
Time Complexity: O(n)
This means the time to create and plot on subplots grows directly with the number of subplots.
[X] Wrong: "Using the pyplot interface is always slower because it calls more functions."
[OK] Correct: Both interfaces do similar work under the hood; the main time cost is plotting each subplot, which grows with n, not the interface choice.
Understanding how plotting time grows helps you explain performance in data visualization tasks clearly and confidently.
What if we changed from plotting on multiple subplots to plotting multiple lines on a single Axes? How would the time complexity change?