Figure layout y subplots
Múltiples gráficos, tamaño, spacing y exportación
Subplots permiten múltiples gráficos en una figura. `fig, axes = plt.subplots(2, 3, figsize=(15, 8))` crea una malla 2×3. `tight_layout()` ajusta automáticamente el espaciamiento para evitar superposición de etiquetas. `figsize=(width, height)` controla el tamaño total.
Exportar correctamente es crítico: PNG 300 dpi para rápido, PDF para vectorial (escalable infinitamente), SVG para edición posterior. `plt.savefig('plot.png', dpi=300, bbox_inches='tight')` guarda de forma profesional.
import matplotlib.pyplot as plt
# === SINGLE SUBPLOT ===
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot([1, 2, 3, 4])
ax.set_title('Title')
# === MULTIPLE SUBPLOTS GRID ===
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
# axes is 2D array: axes[0, 0], axes[0, 1], ..., axes[1, 2]
axes[0, 0].plot([1, 2, 3])
axes[0, 1].scatter([1, 2, 3], [1, 4, 9])
axes[0, 2].hist([1, 2, 2, 3, 3, 3], bins=3)
axes[1, 0].boxplot([[1, 2, 3], [2, 4, 6]])
axes[1, 1].bar(['a', 'b', 'c'], [10, 20, 15])
axes[1, 2].text(0.5, 0.5, 'Text')
plt.tight_layout() # auto-adjust spacing
# === UNEVEN LAYOUT (GridSpec) ===
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(12, 6))
gs = gridspec.GridSpec(2, 2)
ax1 = fig.add_subplot(gs[0, :]) # top spans 2 columns
ax2 = fig.add_subplot(gs[1, 0]) # bottom-left
ax3 = fig.add_subplot(gs[1, 1]) # bottom-right
# === SAVE ===
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
plt.savefig('plot.pdf') # vectorial, scalableDebugging lab
Detecta y corrige el error en el código.
- 01
# 4 plots crammed, labels overlap fig, axes = plt.subplots(2, 2) axes[0, 0].hist(data1, bins=20) axes[0, 1].scatter(x1, y1) axes[1, 0].plot(x2, y2) axes[1, 1].bar(categories, values) plt.show() # crowded, unreadable