What will be the output of the following code that creates nested subplots using subfigures in matplotlib?
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) fig = plt.figure(constrained_layout=True) subfigs = fig.subfigures(1, 2) ax1 = subfigs[0].subplots(2, 1) ax1[0].plot(x, np.sin(x)) ax1[1].plot(x, np.cos(x)) ax2 = subfigs[1].subplots(1, 2) ax2[0].plot(x, np.tan(x)) ax2[1].plot(x, np.exp(-x)) plt.show()
Think about how subfigures split the main figure and how subplots inside each subfigure arrange axes.
The code creates a main figure split into two subfigures horizontally. The left subfigure has two rows of plots (sin and cos), and the right subfigure has two columns of plots (tan and exp decay). This matches option B.
How many total axes (individual plots) are created by the following code?
import matplotlib.pyplot as plt fig = plt.figure() subfigs = fig.subfigures(2, 1) ax_top = subfigs[0].subplots(1, 3) ax_bottom = subfigs[1].subplots(2, 2) print(len(ax_top) + ax_bottom.size)
Count the number of axes in each subfigure and add them.
The top subfigure has 1 row and 3 columns → 3 axes. The bottom subfigure has 2 rows and 2 columns → 4 axes. Total axes = 3 + 4 = 7. However, ax_bottom.size returns 4, and len(ax_top) returns 3, so the print outputs 7.
What error will this code raise?
import matplotlib.pyplot as plt fig = plt.figure() subfigs = fig.subfigures(1, 2) ax = subfigs.subplots(2, 2) plt.show()
Check the type of subfigs and what methods it supports.
fig.subfigures(1, 2) returns a numpy array of SubFigure objects. Calling subfigs.subplots(2, 2) tries to call subplots on a numpy array, which does not have that method. This causes an AttributeError.
Which option best describes the layout of the figure created by this code?
import matplotlib.pyplot as plt fig = plt.figure(constrained_layout=True) subfigs = fig.subfigures(2, 1) ax1 = subfigs[0].subplots(1, 2) ax2 = subfigs[1].subplots(3, 1) plt.show()
Look at the subfigures(2, 1) call and how subplots are arranged inside each subfigure.
The main figure is split into two subfigures stacked vertically. The top subfigure has 1 row and 2 columns (two plots side by side). The bottom subfigure has 3 rows and 1 column (three plots stacked vertically). This matches option C.
You want to create a figure with three subfigures arranged horizontally. The first subfigure has a 2x1 grid of plots, the second subfigure has a single plot, and the third subfigure has a 2x2 grid of plots. Which code snippet correctly creates this layout?
Remember the first argument to subfigures is rows, second is columns. Match the grids inside each subfigure carefully.
Option A correctly creates one row and three columns of subfigures. The first subfigure has 2 rows and 1 column, the second has 1 plot, and the third has 2 rows and 2 columns. Other options either swap rows and columns or assign wrong grids.