Python / Data Science Essentials Interview Questions
How do you create multi-panel figures with Matplotlib subplots?
Multi-panel figures are standard in data science reports — comparing multiple variables or time periods side by side. Matplotlib provides several ways to arrange subplots.
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 200) # --- Regular grid --- fig, axes = plt.subplots(2, 2, figsize=(10, 8), sharex=True) # sharex=True links x-axis zoom/pan across all subplots axes[0, 0].plot(x, np.sin(x)) axes[0, 0].set_title('sin') axes[0, 1].plot(x, np.cos(x), color='tomato') axes[0, 1].set_title('cos') axes[1, 0].plot(x, np.tan(x)) axes[1, 0].set_title('tan') axes[1, 1].set_visible(False) # hide unused subplot fig.suptitle('Trig functions', fontsize=16) fig.tight_layout(rect=[0, 0, 1, 0.95]) # leave room for suptitle # --- Flatten for iteration --- fig, axes = plt.subplots(2, 3, figsize=(14, 6)) for ax, col in zip(axes.flatten(), df.select_dtypes('number').columns): ax.hist(df[col].dropna(), bins=20) ax.set_title(col) # --- GridSpec for irregular layouts --- from matplotlib.gridspec import GridSpec fig = plt.figure(figsize=(12, 6)) gs = GridSpec(2, 3, figure=fig) ax1 = fig.add_subplot(gs[0, :2]) # spans first two columns of row 0 ax2 = fig.add_subplot(gs[0, 2]) # third column of row 0 ax3 = fig.add_subplot(gs[1, :]) # entire row 1
axes.flatten() is the standard idiom when you want to loop over a 2-D grid of Axes objects as if they were a 1-D list. fig.tight_layout() automatically adjusts spacing to prevent labels overlapping between subplots — call it before plt.show() or fig.savefig().
More Related questions...