Hoofdstuk 22 — Veelgebruikte grafieken: line, bar, histogram, box en scatter
Let op: De tekst is in het Nederlands; alle Python codevoorbeelden zijn in het Engels.
Doel van dit hoofdstuk:
- Leren wanneer je lijn-, staaf-, histogram-, box- en scatterplots gebruikt.
- OO‑stijl van Matplotlib toepassen voor deze grafieken.
- Assen schalen, labels, legendes en error bars toevoegen.
- Veelvoorkomende varianten (stacked bars, twin axes, log‑schalen) en valkuilen.
Aanbevolen voorkennis: Hoofdstuk 21 (Matplotlib basis).
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
22.1 Lijngrafieken (line)
Gebruik voor trends over een continue as (tijd, meting per x).
x = np.linspace(0, 10, 200)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, label='sin(x)', color='C0')
ax.set(xlabel='x', ylabel='y', title='Line plot')
ax.legend(); fig.tight_layout()
Varianten:
- Meerdere lijnen per Axes; zorg voor goed onderscheid in kleur/linestyle.
- Log‑schalen:
ax.set_yscale('log')ofax.semilogy(x, y).
22.2 Staafdiagrammen (bar)
Categorische vergelijkingen of geaggregeerde waarden.
cats = ['A','B','C']
vals = [5, 3, 7]
fig, ax = plt.subplots()
ax.bar(cats, vals, color='C1', alpha=0.9)
ax.set(ylabel='count', title='Bar chart')
Horizontaal en gegroepeerd/gestapeld:
# Horizontaal
fig, ax = plt.subplots()
ax.barh(cats, vals)
# Gegroepeerd
vals2 = [4, 2, 6]
idx = np.arange(len(cats))
width = 0.4
fig, ax = plt.subplots()
ax.bar(idx - width/2, vals, width, label='2024')
ax.bar(idx + width/2, vals2, width, label='2025')
ax.set_xticks(idx); ax.set_xticklabels(cats)
ax.legend()
# Gestapeld
fig, ax = plt.subplots()
ax.bar(cats, vals, label='A')
ax.bar(cats, vals2, bottom=vals, label='B')
ax.legend()
Error bars:
means = np.array([5.0, 3.2, 7.1]); errs = np.array([0.6, 0.4, 0.8])
fig, ax = plt.subplots()
ax.bar(cats, means, yerr=errs, capsize=4)
22.3 Histogrammen (hist)
Verdelingen van continue variabelen.
data = rng.normal(loc=0, scale=1, size=10_000)
fig, ax = plt.subplots()
ax.hist(data, bins=40, density=True, alpha=0.7, color='C2')
ax.set(title='Histogram', xlabel='value', ylabel='density')
Tips:
- Kies aantal bins bewust (
bins=of regels zoals Freedman–Diaconis via numpy). - Voor meerdere reeksen:
histtype='step'of transparantie (alpha).
22.4 Boxplots en violins
Samenvatten van verdelingen en outliers.
g1 = rng.normal(0.0, 1.0, 500)
g2 = rng.normal(1.5, 0.8, 500)
fig, ax = plt.subplots()
ax.boxplot([g1, g2], labels=['G1','G2'], showmeans=True)
ax.set(title='Box plot')
# Violinplot
fig, ax = plt.subplots()
ax.violinplot([g1, g2], showmeans=True, showmedians=True)
ax.set_xticks([1,2]); ax.set_xticklabels(['G1','G2'])
22.5 Scatterplots
Relatie tussen twee continue variabelen; kleur/marker/maat voor extra dimensies.
x = rng.normal(0, 1, 1000)
y = 2*x + rng.normal(0, 1, 1000)
size = 20 + 80*rng.random(1000)
color = x
fig, ax = plt.subplots()
sc = ax.scatter(x, y, c=color, s=size, cmap='viridis', alpha=0.7)
ax.set(xlabel='x', ylabel='y', title='Scatter')
cb = fig.colorbar(sc, ax=ax, label='x value')
Regressielijn (simpel) met NumPy:
coef = np.polyfit(x, y, deg=1)
xs = np.linspace(x.min(), x.max(), 100)
ax.plot(xs, coef[0]*xs + coef[1], color='k', lw=2, label='fit')
ax.legend()
22.6 Twin axes en secundaire as
x = np.linspace(0, 10, 200)
y1 = np.sin(x); y2 = np.cos(x)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, color='C0'); ax1.set_ylabel('sin')
ax2.plot(x, y2, color='C3'); ax2.set_ylabel('cos')
22.7 Log‑schalen en breaks
x = np.logspace(0, 4, 200)
y = 1/x
fig, ax = plt.subplots()
ax.loglog(x, y)
ax.set(title='Log–log')
22.8 Veelvoorkomende valkuilen
- Gebruik geen 3D voor 2D‑relaties; vermijdt chartjunk.
- Y‑as nul‑afsnede belangrijk bij staafdiagrammen (anders misleidend), tenzij goed gemotiveerd.
- Overplotting in scatter → gebruik alpha, kleinere markers, of hexbin/density.
- Denk aan kleurenblindvriendelijke paletten (bv.
tab10,colorcetbuiten scope).
22.9 Samenvatting
- Line: trends; Bar: categorieën; Hist/Box/Violin: verdelingen; Scatter: correlaties.
- Voeg labels, legendes, error bars en passende schalen toe.
- OO‑stijl blijft de aanbevolen werkwijze.