Here, plots cover different parts of the grid for a custom layout.
Matplotlib
gs = GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :2]) # Top row, first two columns
ax2 = fig.add_subplot(gs[1:, 2]) # Last two rows, last column
Sample Program
This code creates a figure with 4 plots arranged in a 2x3 grid. Each plot uses different grid cells to create a complex layout.
B. SyntaxError due to missing parentheses in GridSpec.
C. IndexError because row index 2 is out of range for 2 rows.
D. No error; code runs fine.
Solution
Step 1: Check GridSpec size
GridSpec(2, 2) creates 2 rows indexed 0 and 1 only.
Step 2: Check subplot indexing
gs[2, 1] tries to access row 2, which does not exist, causing IndexError.
Final Answer:
IndexError because row index 2 is out of range for 2 rows. -> Option C
Quick Check:
Index out of range = IndexError [OK]
Hint: Check GridSpec row/column indices start at 0 [OK]
Common Mistakes:
Assuming indices start at 1
Confusing syntax errors with index errors
Ignoring zero-based indexing
5. You want to create a figure with 3 subplots: one large plot on the left spanning all rows, and two smaller plots stacked vertically on the right. Which GridSpec slicing correctly achieves this layout for gs = GridSpec(2, 2)?
hard
A. Left plot: gs[0, :], Right top: gs[1, 0], Right bottom: gs[1, 1]
B. Left plot: gs[:, 1], Right top: gs[0, 0], Right bottom: gs[1, 0]
C. Left plot: gs[0, 0], Right top: gs[0, 1], Right bottom: gs[1, 1]
D. Left plot: gs[:, 0], Right top: gs[0, 1], Right bottom: gs[1, 1]
Solution
Step 1: Understand layout goal
Left plot spans all rows in first column; right side has two stacked plots in second column.
Step 2: Match slicing to layout
gs[:, 0] selects all rows in column 0 (left plot). gs[0, 1] and gs[1, 1] select top and bottom right plots.
Final Answer:
Left plot: gs[:, 0], Right top: gs[0, 1], Right bottom: gs[1, 1] -> Option D
Quick Check:
Use colon for full rows, index for columns [OK]
Hint: Use colon to span all rows or columns in GridSpec [OK]
Common Mistakes:
Mixing row and column indices
Using single indices instead of slices for spanning
Swapping left and right columns
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.