Shared axes between subplots in Matplotlib - Time & Space Complexity
We want to understand how the time to create plots changes when we share axes between subplots in matplotlib.
How does sharing axes affect the work matplotlib does as we add more subplots?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 1, sharex=True, sharey=True)
for i, ax in enumerate(axs):
ax.plot([0, 1, 2], [i, i+1, i+2])
plt.show()
This code creates three vertical subplots that share the same x and y axes, then plots simple lines on each.
- Primary operation: Looping over each subplot to draw a line plot.
- How many times: Once per subplot, here 3 times.
As the number of subplots increases, matplotlib draws each plot once but shares axis settings.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 plot draws + 1 shared axis setup |
| 10 | 10 plot draws + 1 shared axis setup |
| 100 | 100 plot draws + 1 shared axis setup |
Pattern observation: The main work grows linearly with the number of subplots, while axis setup is done once.
Time Complexity: O(n)
This means the time to create and draw plots grows directly with the number of subplots.
[X] Wrong: "Sharing axes means the time stays the same no matter how many subplots there are."
[OK] Correct: Sharing axes saves some work on axis setup, but each subplot still needs its own plot drawn, so time grows with the number of subplots.
Understanding how shared axes affect plotting time helps you explain performance when working with multiple charts, a useful skill in data visualization tasks.
What if we did not share axes between subplots? How would the time complexity change?