Figure and Axes mental model in Matplotlib - Time & Space Complexity
When working with matplotlib, it is helpful to understand how the figure and axes objects behave in terms of time cost.
We want to know how the time to create and update plots grows as we add more axes or figures.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 3)
for ax in axs.flat:
ax.plot([1, 2, 3], [1, 4, 9])
plt.show()
This code creates a 3 by 3 grid of axes and plots a simple line on each axes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each axes to plot data.
- How many times: Once for each axes, here 9 times (3 rows x 3 columns).
As the number of axes increases, the time to plot on each axes grows linearly.
| Input Size (number of axes) | Approx. Operations |
|---|---|
| 10 | 10 plotting calls |
| 100 | 100 plotting calls |
| 1000 | 1000 plotting calls |
Pattern observation: Doubling the number of axes roughly doubles the work done.
Time Complexity: O(n)
This means the time to create and plot on axes grows directly with the number of axes.
[X] Wrong: "Adding more axes does not affect plotting time much because each plot is simple."
[OK] Correct: Even simple plots take time, and plotting on many axes adds up linearly.
Understanding how plotting time grows with the number of axes helps you design efficient visualizations and manage resources well.
"What if we changed the code to plot multiple lines on each axes? How would the time complexity change?"