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 1axes.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().
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
