Individual subplot customization in Matplotlib - Time & Space Complexity
When customizing individual subplots in matplotlib, we want to know how the time to draw changes as we add more subplots.
How does the work grow when we customize each subplot separately?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 3)
for i, ax in enumerate(axs.flat):
ax.plot([0, 1, 2], [i, i*2, i*3])
ax.set_title(f"Plot {i+1}")
plt.show()
This code creates a 3x3 grid of subplots and customizes each one by plotting data and setting a title.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each subplot to customize it.
- How many times: Once for each subplot, here 9 times (3 rows x 3 columns).
Each subplot requires a fixed amount of work to customize. As the number of subplots grows, the total work grows proportionally.
| Input Size (n subplots) | Approx. Operations |
|---|---|
| 10 | 10 customization steps |
| 100 | 100 customization steps |
| 1000 | 1000 customization steps |
Pattern observation: Doubling the number of subplots roughly doubles the work needed.
Time Complexity: O(n)
This means the time to customize grows directly in proportion to the number of subplots.
[X] Wrong: "Customizing multiple subplots is done all at once, so time stays the same no matter how many subplots there are."
[OK] Correct: Each subplot needs its own commands, so the total time adds up with more subplots.
Understanding how work grows when customizing plots helps you write efficient code and explain your approach clearly in real projects.
"What if we customized only a fixed number of subplots regardless of total? How would the time complexity change?"
Practice
fig, axs = plt.subplots(2, 2)?Solution
Step 1: Understand subplot indexing
Withplt.subplots(2, 2),axsis a 2x2 array. The second subplot in the first row is at position [0, 1].Step 2: Set title for specific subplot
Useaxs[0, 1].set_title('New Title')to change only that subplot's title.Final Answer:
Useaxs[0, 1].set_title('New Title')-> Option DQuick Check:
Indexing subplots by row and column = A [OK]
- Using axs[1] instead of axs[0, 1]
- Setting title on fig instead of axs
- Using plt.title affects whole figure, not subplot
fig, axs = plt.subplots(3)?Solution
Step 1: Identify subplot indexing in 1D array
Withplt.subplots(3),axsis a 1D array with indices 0, 1, 2. The first subplot is at index 0.Step 2: Use set_xlabel on the correct subplot
Useaxs[0].set_xlabel('X Label')to set the x-axis label of the first subplot.Final Answer:
axs[0].set_xlabel('X Label') -> Option BQuick Check:
Index 0 for first subplot in 1D axs = D [OK]
- Using axs[1] for first subplot
- Calling set_xlabel on fig or axs directly
- Confusing 1D and 2D axs indexing
import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) axs[1, 0].plot([1, 2, 3], [4, 5, 6], color='green') plt.show()
Solution
Step 1: Identify subplot position
Withplt.subplots(2, 2), subplots are indexed as [0,0], [0,1], [1,0], [1,1]. The third subplot is at [1,0].Step 2: Check plot color argument
The code setscolor='green'for the line in subplot [1,0].Final Answer:
Green -> Option CQuick Check:
Color set explicitly to green = B [OK]
- Assuming default blue color
- Confusing subplot index order
- Ignoring color parameter in plot
fig, axs = plt.subplots(2, 2)
axs[2, 1].set_ylabel('Y Label')Solution
Step 1: Check axs shape and indexing
Withplt.subplots(2, 2), axs shape is (2, 2), valid indices are 0 or 1 for each dimension.Step 2: Identify invalid index
Indexing axs[2, 1] tries to access third row (index 2), which does not exist, causing IndexError.Final Answer:
IndexError because axs has shape (2,2) and index (2,1) is out of range -> Option AQuick Check:
Index out of range error = C [OK]
- Assuming axs has more rows than created
- Confusing AttributeError with IndexError
- Using wrong indexing syntax
Solution
Step 1: Understand axs structure and iteration
Withplt.subplots(2, 2), axs is a 2D array. Usingaxs.flatflattens it to 1D for easy iteration.Step 2: Apply colors correctly
Usingzip(axs.flat, colors)pairs each subplot with a color. Callingax.set_facecolor(color)sets background color individually.Final Answer:
Use axs.flat with zip and set_facecolor for each subplot -> Option AQuick Check:
Flatten axs and zip with colors = A [OK]
- Trying to index axs as 1D without flattening
- Using axs as 2D but wrong color indexing
- Passing full color list to set_facecolor
Ready to prove it?
Pass the test and this pattern moves unknown
