Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Hoofdstuk 25 — Integratie met pandas en NumPy; theming en rcParams

Let op: De tekst is in het Nederlands; alle Python codevoorbeelden zijn in het Engels.

Doel van dit hoofdstuk:

  • Efficiënt plotten met pandas (DataFrame.plot, Series.plot) op Matplotlib‑Axes.
  • NumPy‑integratie: imshow, contour, pcolormesh, en colormaps.
  • Theming met styles, rcParams en color cyclers; consistente lay‑out voor projecten.
  • Praktische tips voor lettertypen, colormaps, en globale figuurinstellingen.

Aanbevolen voorkennis: Hoofdstuk 21–24, basis pandas/NumPy.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl

25.1 pandas plot‑API op Matplotlib‑Axes

pandas bouwt bovenop Matplotlib. Gebruik OO‑stijl door ax= te mee te geven.

# Voorbeeld‑data
rng = np.random.default_rng(0)
dates = pd.date_range('2025-01-01', periods=50, freq='D')
df = pd.DataFrame({
    'A': np.cumsum(rng.normal(0, 1, 50)),
    'B': np.cumsum(rng.normal(0, 1, 50)),
}, index=dates)

fig, ax = plt.subplots(figsize=(7, 3))
df.plot(ax=ax)
ax.set(title='pandas line plot', xlabel='date', ylabel='value')
ax.legend(title='series')
fig.tight_layout()

Veelgebruikte opties:

  • kind='bar'|'barh'|'hist'|'box'|'kde'|'area'|'scatter'|'hexbin'.
  • subplots=True om elke kolom apart te plotten (terug: array van Axes).
  • layout=(rows, cols) voor subplots raster.
  • sharex=True|False, sharey=True|False voor gedeelde assen.
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)
df[['A']].plot(kind='area', alpha=0.4, ax=axes[0])
df[['B']].plot(kind='area', alpha=0.4, ax=axes[1], color='C3')
for ax, t in zip(axes, ['A','B']):
    ax.set_title(t)
fig.suptitle('pandas area'); fig.tight_layout()

25.2 pandas scatter en hexbin

N = 2000
xy = pd.DataFrame({
    'x': rng.normal(size=N),
    'y': rng.normal(size=N)
})
fig, ax = plt.subplots(figsize=(5, 4))
xy.plot(kind='scatter', x='x', y='y', s=10, alpha=0.5, ax=ax)
ax.set_title('pandas scatter')

# Hexbin voor hoge dichtheid
fig, ax = plt.subplots(figsize=(5, 4))
xy.plot(kind='hexbin', x='x', y='y', gridsize=30, cmap='viridis', ax=ax)
ax.set_title('pandas hexbin')

25.3 NumPy‑beelden met imshow/pcolormesh/contour

# 2D rasterdata
gx, gy = np.mgrid[-3:3:0.05, -3:3:0.05]
Z = np.exp(-(gx**2 + gy**2)) * np.cos(2*gx) * np.sin(2*gy)

fig, axes = plt.subplots(1, 3, figsize=(12, 3))
im = axes[0].imshow(Z, origin='lower', cmap='viridis')
fig.colorbar(im, ax=axes[0], shrink=0.8, label='value')

pc = axes[1].pcolormesh(gx, gy, Z, shading='auto', cmap='magma')
fig.colorbar(pc, ax=axes[1], shrink=0.8)

cs = axes[2].contour(gx, gy, Z, levels=12, colors='k', linewidths=0.7)
axes[2].clabel(cs, inline=True, fontsize=8)
for ax in axes:
    ax.set(xlabel='x', ylabel='y')
fig.suptitle('NumPy rasterplots'); fig.tight_layout()

Colormap tips:

  • Gebruik perceptueel uniforme colormaps (viridis, magma, cividis).
  • Gebruik norm=mpl.colors.LogNorm() voor positieve grootheden met grote range.

25.4 Stylesheet en rcParams voor projectthema

Je kunt projectbrede stijl vastleggen via rcParams of een custom stylesheet.

# Tijdelijk een style toepassen
with plt.style.context('seaborn-v0_8'):
    fig, ax = plt.subplots()
    df.plot(ax=ax); ax.set_title('Seaborn context')

# rcParams: globaal aanpassen
mpl.rcParams.update({
    'figure.dpi': 150,
    'axes.grid': True,
    'axes.titlesize': 12,
    'axes.labelsize': 10,
    'legend.frameon': False,
})

Eigen stylebestand (optioneel): maak een .mplstyle file en laad met plt.style.use('pad/naar/custom.mplstyle').

25.5 Color cycler en consistente palettes

from cycler import cycler
cycle = cycler(color=['#1f77b4','#ff7f0e','#2ca02c','#d62728']) + cycler(linestyle=['-','--','-.',':'])
mpl.rcParams['axes.prop_cycle'] = cycle

fig, ax = plt.subplots()
for k in range(4):
    ax.plot(np.linspace(0, 1, 50), np.linspace(0, 1, 50)**(k+1), label=f'k={k+1}')
ax.legend(); ax.set_title('Custom cycler')

25.6 Lettertypen en symbolen

# Kies een font familie (let op beschikbaarheid in je systeem)
mpl.rcParams['font.family'] = 'DejaVu Sans'
# Wetenschappelijke notatie en minus teken correct
mpl.rcParams['axes.unicode_minus'] = True

Voor LaTeX‑rendering (optioneel, vereist TeX‑installatie):

# mpl.rcParams['text.usetex'] = True

25.7 Integratiepatronen met pandas → Matplotlib

  • Gebruik pandas voor aggregatie/reshaping; plot op door jou aangemaakte Axes.
  • Geef ax= door en zet titels/labels via Matplotlib, niet mixen met pandas titels.
  • Werk met constrained_layout=True bij plt.figure(..., constrained_layout=True) voor automatische layout.
agg = (df.resample('7D').mean()
         .rename(columns={'A':'A_mean','B':'B_mean'}))
fig, ax = plt.subplots(figsize=(7,3), constrained_layout=True)
agg.plot(ax=ax)
ax.set(title='7‑daags gemiddelde', xlabel='date', ylabel='value')

25.8 Valkuilen en best practices

  • pandas plot(kind=...) is handig, maar voor maatwerk: werk op Matplotlib‑Axes.
  • Mix niet te veel automatische styling van pandas met rcParams; kies één pad.
  • Standaard colormap jet vermijden; kies perceptueel uniforme opties.

25.9 Samenvatting

  • pandas integreert direct met Matplotlib via ax=; gebruik het voor snelle exploratie.
  • NumPy‑rasterdata visualiseer je met imshow/pcolormesh/contour + passende colormap/norm.
  • Stylesheets, rcParams en cyclers zorgen voor consistente theming in projecten.