0
0
Matplotlibdata~5 mins

Figure and Axes mental model in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Figure and Axes mental model
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the number of axes increases, the time to plot on each axes grows linearly.

Input Size (number of axes)Approx. Operations
1010 plotting calls
100100 plotting calls
10001000 plotting calls

Pattern observation: Doubling the number of axes roughly doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time to create and plot on axes grows directly with the number of axes.

Common Mistake

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

Interview Connect

Understanding how plotting time grows with the number of axes helps you design efficient visualizations and manage resources well.

Self-Check

"What if we changed the code to plot multiple lines on each axes? How would the time complexity change?"