Small multiples (facet grid) in Matplotlib - Time & Space Complexity
When creating small multiples with matplotlib, we want to know how the time to draw charts grows as we add more plots.
How does adding more small charts affect the total work matplotlib does?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(3, 3)
for i, ax in enumerate(axs.flat):
x = np.linspace(0, 10, 100)
y = np.sin(x + i)
ax.plot(x, y)
plt.show()
This code creates a 3 by 3 grid of small plots, each showing a sine wave shifted by a different amount.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each subplot to draw a line plot.
- How many times: Once for each subplot, here 9 times (3 rows x 3 columns).
Each additional small plot adds roughly the same amount of work to draw its line.
| Input Size (number of plots) | Approx. Operations |
|---|---|
| 10 | 10 times the work to draw one plot |
| 100 | 100 times the work to draw one plot |
| 1000 | 1000 times the work to draw one plot |
Pattern observation: The total work grows directly with the number of small plots.
Time Complexity: O(n)
This means the time to draw all small multiples grows linearly as you add more plots.
[X] Wrong: "Adding more small plots only slightly increases drawing time because they are small."
[OK] Correct: Each plot still requires its own drawing steps, so total time adds up directly with the number of plots.
Understanding how drawing many small charts scales helps you design efficient visualizations and explain performance trade-offs clearly.
What if we changed the number of points in each plot from 100 to 1000? How would the time complexity change?