Hoofdstuk 21 — Matplotlib basis: Figure, Axes, styles en layouts
Let op: De tekst is in het Nederlands; alle Python codevoorbeelden zijn in het Engels.
Doel van dit hoofdstuk:
- Begrijpen van de Matplotlib‑architectuur: Figure, Axes en Artists.
- Leren werken met de object‑georiënteerde (OO) interface i.p.v. de stateful
pyplotshortcuts. - Styles, kleuren, markers en lijnen instellen.
- Layouts en meerdere subplot‑rasterindelingen maken en beheren.
Aanbevolen voorkennis: Hoofdstuk 13–20 (pandas/NumPy). Installeer Matplotlib:
pip install matplotlib
21.1 Figure en Axes: de kern
Matplotlib tekent op Axes (plotvlak) binnen een Figure (canvas/figuur). Gebruik bij voorkeur de OO‑stijl.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 200)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(6, 4), dpi=120)
ax.plot(x, y, label='sin(x)')
ax.set(title='Sine', xlabel='x', ylabel='y')
ax.legend()
fig.tight_layout()
plt.show()
Belangrijkste concepten:
- Figure: het gehele canvas (afbeelding), bevat 1+ Axes.
- Axes: de plot zelf met assen, ticks, labels, titel en artists (lijnen, scatter, patches).
- OO‑API:
ax.plot(...)i.p.v.plt.plot(...)voor expliciete controle.
21.2 Lijnen, markers, kleuren en stijlen
fig, ax = plt.subplots()
ax.plot(x, y, color='C0', linewidth=2, linestyle='-', marker='o', markersize=4)
ax.plot(x, np.cos(x), color='#d62728', lw=1.5, ls='--', label='cos(x)')
ax.set_xlabel('x'); ax.set_ylabel('f(x)'); ax.legend()
Tips:
- Gebruik cycler‑kleuren (
C0..C9) of hex‑kleuren. - Transparantie via
alpha=. - Markers:
'o','^','s','.', etc.
21.3 Assen, limieten, ticks en grids
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 2*np.pi); ax.set_ylim(-1.1, 1.1)
ax.set_xticks([0, np.pi, 2*np.pi]); ax.set_xticklabels(['0', 'π', '2π'])
ax.grid(True, axis='both', linestyle=':', alpha=0.6)
21.4 Meerdere subplots en layouts
# 1x2 raster
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)
axes[0].plot(x, np.sin(x)); axes[0].set_title('sin')
axes[1].plot(x, np.cos(x)); axes[1].set_title('cos')
fig.suptitle('Trig'); fig.tight_layout()
Geavanceerde layout hulpmiddelen:
fig.tight_layout()ofplt.tight_layout()voor automatische marges.fig.subplots_adjust(...)voor handmatige marge‑tuning.matplotlib.gridspecvoor ongelijke rasters.
21.5 Styles en theming
Matplotlib heeft ingebouwde styles (themes).
import matplotlib.pyplot as plt
plt.style.available[:5]
with plt.style.context('seaborn-v0_8'):
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set(title='Seaborn‑style')
Eigen rcParams aanpassen:
import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 150
mpl.rcParams['axes.grid'] = True
21.6 Tekst, annotaties en legendes (basis)
fig, ax = plt.subplots()
ax.plot(x, y, label='sin')
ax.legend(loc='best')
ax.set_title('Titel')
ax.annotate('maximum', xy=(np.pi/2, 1), xytext=(2, 1.2),
arrowprops=dict(arrowstyle='->'))
21.7 Opslaan van figuren
fig.savefig('plot.png', dpi=150, bbox_inches='tight')
fig.savefig('plot.pdf') # vector
21.8 Veelvoorkomende valkuilen
- Gemixte OO‑ en pyplot‑stijl kan verwarrend zijn. Kies consequent voor OO.
- Vergeet
tight_layout()ofbbox_inches='tight'niet bij saven om afgesneden labels te voorkomen. - Houd rekening met DPI en figsize voor leesbaarheid.
21.9 Samenvatting
- Gebruik
plt.subplots()om Figure en Axes te krijgen. - Werk met de OO‑API (
ax.plot,ax.set,ax.legend) voor controle en compositie. - Styles/rcParams bepalen de look; layouts regelen de rangschikking van subplots.