0
0
Matplotlibdata~5 mins

Shared axes between subplots in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Shared axes between subplots
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Looping over each subplot to draw a line plot.
  • How many times: Once per subplot, here 3 times.
How Execution Grows With Input

As the number of subplots increases, matplotlib draws each plot once but shares axis settings.

Input Size (n)Approx. Operations
33 plot draws + 1 shared axis setup
1010 plot draws + 1 shared axis setup
100100 plot draws + 1 shared axis setup

Pattern observation: The main work grows linearly with the number of subplots, while axis setup is done once.

Final Time Complexity

Time Complexity: O(n)

This means the time to create and draw plots grows directly with the number of subplots.

Common Mistake

[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.

Interview Connect

Understanding how shared axes affect plotting time helps you explain performance when working with multiple charts, a useful skill in data visualization tasks.

Self-Check

What if we did not share axes between subplots? How would the time complexity change?