Consider the following Python code using matplotlib to create a plot with tight layout:
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [1, 4, 9]) fig.tight_layout() print(fig.subplotpars.left, fig.subplotpars.right)
What will be printed?
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [1, 4, 9]) fig.tight_layout() print(round(fig.subplotpars.left, 2), round(fig.subplotpars.right, 2))
tight_layout adjusts subplot parameters to give specified padding.
After calling fig.tight_layout(), the subplot parameters adjust to fit the plot tightly. The left and right margins typically become around 0.1 and 0.95 respectively.
Given this code creating multiple subplots:
import matplotlib.pyplot as plt fig, axs = plt.subplots(3, 3) fig.tight_layout() print(len(axs.flatten()))
What is the output?
import matplotlib.pyplot as plt fig, axs = plt.subplots(3, 3) fig.tight_layout() print(len(axs.flatten()))
Count total subplots created in a 3x3 grid.
3 rows and 3 columns create 9 subplots total. tight_layout does not change the number of subplots.
Which code snippet will produce a plot where x-axis labels do not overlap, using tight layout?
tight_layout helps adjust spacing automatically for rotated labels.
Option D uses fig.tight_layout() after rotating x-axis labels, which prevents overlap by adjusting margins automatically.
Given this code:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 1)
axs[0].set_title('Title 1')
axs[1].set_title('Title 2')
fig.tight_layout()
plt.show()Why might the titles still overlap?
Consider what tight_layout adjusts automatically.
tight_layout adjusts subplot parameters but does not reserve space for axes titles or suptitles automatically, so titles can overlap.
You want to create a figure with multiple subplots and avoid label and title overlaps. Which approach is best?
constrained_layout is a newer layout manager than tight_layout.
Using constrained_layout=True when creating the figure automatically manages spacing better than tight_layout, so calling both is not recommended.