Consider the following code using matplotlib.gridspec.GridSpec. What will be the number of subplots created and their arrangement?
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig = plt.figure() gs = GridSpec(3, 3, figure=fig) ax1 = fig.add_subplot(gs[0, :]) ax2 = fig.add_subplot(gs[1, :-1]) ax3 = fig.add_subplot(gs[1:, -1]) ax4 = fig.add_subplot(gs[-1, 0]) plt.close(fig) print(len(fig.axes))
Count each add_subplot call and check if any overlap or replacement occurs.
The code creates 4 subplots using different GridSpec slices. Each add_subplot adds a new axis, so total is 4.
Given this GridSpec code, what is the shape of the grid and which cells does gs[1:3, 0:2] cover?
from matplotlib.gridspec import GridSpec gs = GridSpec(4, 4) covered_cells = [(r, c) for r in range(1, 3) for c in range(0, 2)] print((gs.nrows, gs.ncols), covered_cells)
GridSpec(4,4) creates a 4x4 grid. The slice selects rows 1 and 2, columns 0 and 1.
The GridSpec is 4 rows by 4 columns. The slice 1:3 means rows 1 and 2, and 0:2 means columns 0 and 1, so the covered cells are those four coordinates.
Which option shows the correct layout of subplots created by this code?
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig = plt.figure(figsize=(6, 4)) gs = GridSpec(2, 3, figure=fig) ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[0, 1:]) ax3 = fig.add_subplot(gs[1, :2]) ax4 = fig.add_subplot(gs[1, 2]) plt.close(fig) # The question is about the layout shape, not the plot content.
Look at the slices: gs[0, 0], gs[0, 1:], gs[1, :2], gs[1, 2].
The first subplot is top-left cell. The second spans top row columns 1 and 2. The third spans bottom row columns 0 and 1. The last is bottom row column 2 alone.
What error will this code raise when executed?
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig = plt.figure() gs = GridSpec(2, 2, figure=fig) ax1 = fig.add_subplot(gs[2, 0]) plt.close(fig)
Check the grid size and the index used in gs[2, 0].
The GridSpec has 2 rows (indices 0 and 1). Index 2 is out of range, so an IndexError is raised.
You want to create a figure with two main columns. The left column has two rows of equal height. The right column is a single subplot spanning full height. Which code snippet correctly creates this layout using nested GridSpec?
Think about how to split the figure into two columns, then split the left column into two rows.
Option D uses a nested GridSpec: outer GridSpec(1, 2) splits into two columns. The left column (gs[0, 0]) is subdivided with nested GridSpec(2, 1) into two equal-height rows. The right column (gs[0, 1]) is a single subplot spanning the full height.