Inline display in Jupyter notebooks in Matplotlib - Time & Space Complexity
When we use matplotlib to show plots inside Jupyter notebooks, the way plots are displayed affects how long it takes to show them.
We want to understand how the time to display grows as we create more or bigger plots.
Analyze the time complexity of the following code snippet.
%matplotlib inline
import matplotlib.pyplot as plt
for i in range(n):
plt.plot([0, 1, 2], [i, i+1, i+2])
plt.show()
This code creates and shows n small plots one after another inside the notebook.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs n times, each time creating and displaying one plot.
- How many times: The plot creation and display happen once per loop, so n times total.
As n grows, the total time to create and show all plots grows roughly in direct proportion to n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 plot creations and displays |
| 100 | 100 plot creations and displays |
| 1000 | 1000 plot creations and displays |
Pattern observation: Doubling n doubles the total work because each plot is handled separately.
Time Complexity: O(n)
This means the time to display all plots grows linearly with the number of plots created.
[X] Wrong: "Showing multiple plots inline happens instantly no matter how many plots there are."
[OK] Correct: Each plot requires time to render and display, so more plots mean more total time.
Understanding how plotting time grows helps you write efficient data exploration code and explain performance in real projects.
"What if we create all plots first and call plt.show() only once at the end? How would the time complexity change?"