Skip to content

Matplotlib Spickzettel

Umfassende Python-Plotting-Bibliothek zur Datenvisualisierung.

01

Erste Schritte

Installation & erster Plot

Matplotlib ist die Grundlage des Python-Plottings. pyplot ist das zustandsbasierte Interface (ähnlich MATLAB). Rufe in einem Skript immer plt.show() auf, um die Figure zu rendern; in Jupyter-Notebooks wird die Figure automatisch gerendert, sobald eine Zelle endet.

matplotlib
# install
pip install matplotlib

import matplotlib.pyplot as plt
import numpy as np

# a simple line plot
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()

pyplot-State-Interface

Das pyplot-Interface spiegelt MATLAB wider: Jeder Aufruf wirkt auf die intern verwaltete 'aktuelle' Figure/Axes. Es ist praktisch für schnelle Plots, kann aber bei mehreren Subplots verwirrend werden. Mit plt.gcf()/plt.gca() greifst du auf die aktuellen Figure-/Axes-Objekte zu.

matplotlib
import matplotlib.pyplot as plt

# pyplot tracks the "current" figure and axes
plt.figure()             # create a new figure
plt.plot([1, 2, 3], [4, 5, 2])
plt.title("State-based")  # applies to the current axes
plt.xlim(0, 4)
plt.ylim(0, 6)
plt.show()

# plt.gcf() -> current figure, plt.gca() -> current axes
print(plt.gca())

Figure & Axes (OO-Interface)

Das objektorientierte (OO) Interface ist der empfohlene Ansatz für alles über einen einzelnen Plot hinaus. Du erzeugst eine Figure (die gesamte Leinwand) und eine oder mehrere Axes (einzelne Plots) und rufst Methoden darauf auf. Es skaliert sauber auf Subplots, Twin-Achsen und komplexe Layouts.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

# object-oriented interface: explicit Figure and Axes objects
fig, ax = plt.subplots()      # fig is the canvas, ax is a single Axes
x = np.linspace(0, 5, 50)
ax.plot(x, x**2, label="x^2")
ax.plot(x, x**3, label="x^3")
ax.set_title("OO Interface")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()

Übliche Imports & Konventionen

plt ist der nahezu universelle Alias für pyplot und np für NumPy — fast jedes Tutorial und jede Bibliothek erwartet diese. rcParams ist das globale Konfigurationsverzeichnis: setze es einmal am Anfang eines Skripts, um DPI, Schriftgröße, Figure-Größe und viele weitere Standardwerte festzulegen.

matplotlib
# the universal alias
import matplotlib.pyplot as plt
import numpy as np

# for the OO interface you often see
from matplotlib.figure import Figure
from matplotlib.axes import Axes

# set a global style once
plt.rcParams["figure.dpi"] = 100
plt.rcParams["font.size"] = 11

# inline backend in Jupyter (not needed in scripts)
# %matplotlib inline

Backends & plt.show()

Ein Backend rendert die Figure: Interaktive Backends (TkAgg, Qt5Agg) öffnen ein Fenster, nicht interaktive (Agg) schreiben nur Dateien. Rufe matplotlib.use() vor dem pyplot-Import auf. plt.show() blockiert in Skripten, bis die Fenster geschlossen werden; in Jupyter bettet %matplotlib inline die Figures ins Notebook ein.

matplotlib
import matplotlib

# list available backends
print(matplotlib.rcsetup.all_backends)

# force a backend (do this BEFORE importing pyplot)
# matplotlib.use("Agg")        # non-interactive, for saving files
# matplotlib.use("TkAgg")      # interactive Tk window

import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
# plt.show() blocks until the window is closed
plt.savefig("out.png")  # saving works without any GUI backend
02

Liniendiagramme (plot)

Einfaches Liniendiagramm

plt.plot(x, y) zeichnet eine Linie, die die (x, y)-Punkte der Reihe nach verbindet. Übergibst du nur ein Array, wird es als y verwendet und x standardmäßig auf 0..N-1 gesetzt. plt.grid(True) schaltet Gitterlinien ein/aus. Punkte werden in Array-Reihenfolge verbunden — sortiere x daher zuerst für eine glatte Kurve.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.5)
y = x * 2

plt.plot(x, y)
plt.title("y = 2x")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()

Mehrere Linien

Jeder plt.plot()-Aufruf fügt der aktuellen Axes eine neue Linie hinzu und rückt den Farbzyklus automatisch weiter. Gib jedem einen label= mit, damit plt.legend() sie unterscheiden kann. Matplotlib behandelt Achsengrenzen automatisch und erweitert sie auf den größten Bereich.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.plot(x, np.sin(x) + np.cos(x), label="sin+cos")
plt.legend()
plt.title("Trig Functions")
plt.show()

Linienstile & Marker

Der Format-String 'Farbe+Marker+Linienstil' (z. B. 'ro--') ist kompakt, aber kryptisch. Bevorzuge die expliziten Schlüsselwortargumente color=, marker=, linestyle= für lesbaren Code. Übliche Linienstile: '-' '--' ':' '-.'. Übliche Marker: 'o' 's' '^' 'D' 'v' '+' 'x'.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 20)
# format string: [color][marker][linestyle]
plt.plot(x, x, "r-")        # red solid line
plt.plot(x, x*2, "go--")    # green circles, dashed
plt.plot(x, x*3, "bs:")     # blue squares, dotted
plt.plot(x, x*4, "k^-.")    # black triangles, dash-dot

# explicit kwargs (clearer, recommended)
plt.plot(x, x*5, color="purple", marker="D",
         linestyle="-.", linewidth=2, markersize=6)

Farben

Matplotlib akzeptiert viele Farbformate: Namen ('red'), Hex-Strings ('#FF8800'), RGB(A)-Tupel, Tableau-Namen ('tab:blue'), Zyklus-Referenzen ('C0'..'C9') und Graustufen-Strings ('0.5'). 'C0' wählt die erste Farbe des aktuellen Styles und hält Plots konsistent mit dem Farbzyklus.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 30)
plt.plot(x, x, color="red")              # named color
plt.plot(x, x+0.2, color="#FF8800")      # hex RGB
plt.plot(x, x+0.4, color=(0.1, 0.8, 0.2))# RGB tuple 0-1
plt.plot(x, x+0.6, color="C0")           # cycle color 0
plt.plot(x, x+0.8, color="tab:purple")   # Tableau palette
# gray shorthand: a string of float in [0,1]
plt.plot(x, x+1.0, color="0.5")          # mid gray
plt.show()

Linienbreite, Alpha & zorder

linewidth steuert die Strichstärke (Standard 1.5). alpha legt die Transparenz fest und ist essenziell, wenn sich Kurven überlappen, damit du erkennst, was darunter liegt. zorder steuert die Stapelung — höhere Werte werden später (oben) gezeichnet. Standard-zorder ist 2 für Linien, 1 für Patches.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
# alpha = transparency (0 invisible, 1 opaque)
# zorder = draw order; higher draws on top
plt.fill_between(x, np.sin(x), alpha=0.3, zorder=1)
plt.plot(x, np.sin(x), linewidth=2, zorder=2)
plt.plot(x, np.cos(x), linewidth=4, alpha=0.7, zorder=3)
plt.show()

Step- & Stairs-Plots

plt.step() zeichnet Treppenfunktionen, nützlich für digitale Signale und diskrete Daten; where steuert, wo die Stufe ansteigt ('pre', 'post', 'mid'). plt.stairs() (3.4+) ist das moderne Äquivalent, das y-Werte und separate Bin-Kanten nimmt und gut mit hist-artigen Daten harmoniert.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = [1, 3, 2, 4, 3]

# step: like plot but with horizontal/vertical steps
plt.step(x, y, where="post", label="post")
plt.step(x, y + 1, where="mid", label="mid")
plt.step(x, y + 2, where="pre", label="pre")
plt.legend(title="where=")

# stairs (matplotlib 3.4+): step from explicit bin edges
plt.stairs([1, 2, 1], baseline=0)

plt.show()
03

Streudiagramme

Einfaches Scatter

plt.scatter(x, y) zeichnet Punkte ohne Verbindungslinien. Bei Zehntausenden Punkten ist es langsamer als plt.plot(x, y, 'o'), weil scatter jedem Punkt eigene Größe und Farbe erlaubt. Nutze plt.plot mit Marker für maximale Geschwindigkeit bei einheitlichem Styling.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(0)
x = rng.random(50)
y = rng.random(50)

plt.scatter(x, y)
plt.title("Basic Scatter")
plt.xlabel("x")
plt.ylabel("y")
plt.axis("equal")   # equal aspect ratio
plt.show()

Markergröße & -farbe

Das Argument s ist die Marker-FLÄCHE in Punkten zum Quadrat (nicht Radius) — ein 4x größeres s bedeutet nur den 2-fachen Radius. Das Argument c (Farbe) mit cmap bildet ein numerisches Array auf eine Colormap ab. Verwende alpha < 1, wenn sich Punkte überlappen, damit die Dichte sichtbar bleibt.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(1)
n = 50
x = rng.random(n)
y = rng.random(n)
sizes = rng.random(n) * 500     # area in points^2
colors = rng.random(n)          # mapped to colormap

plt.scatter(x, y, s=sizes, c=colors, cmap="viridis", alpha=0.6)
plt.colorbar(label="value")
plt.title("Bubble Chart")
plt.show()

Colormap-Scatter

Ein 1-D-Array an c bildet jeden Punkt auf eine Colormap ab; plt.colorbar(sc) fügt einen Colorbar hinzu (übergib den Rückgabewert des Scatter, damit der Colorbar die Zuordnung kennt). vmin/vmax fixieren den Colormap-Bereich; ohne sie skaliert matplotlib automatisch auf Min/Max der Daten.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 200)
y = np.sin(x)
c = x           # color by x value

sc = plt.scatter(x, y, c=c, cmap="plasma", vmin=0, vmax=10)
cb = plt.colorbar(sc)
cb.set_label("x position")
plt.title("Colored by x")
plt.show()

Transparenz & Overplotting

Bei vielen überlappenden Punkten verdeckt ein voller Scatter die Dichte. Setze alpha auf ~0.05 und verkleinere den Marker, um Strukturen sichtbar zu machen. Bei sehr großen Datenmengen (100k+ Punkte) aggregieren plt.hexbin oder plt.hist2d in Bins — schneller und übersichtlicher als roher Scatter.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(2)
n = 5000
x = rng.normal(0, 1, n)
y = rng.normal(0, 1, n)

# dense scatter: low alpha reveals density
plt.scatter(x, y, s=5, alpha=0.05, c="navy")
plt.title("Density via alpha")

# alternative: hexbin for very large datasets
plt.figure()
plt.hexbin(x, y, gridsize=40, cmap="Blues")
plt.colorbar(label="count")
plt.show()

Kategorialer Scatter

Matplotlib hat keinen eingebauten Strip-Plot, daher ist Scatter mit manuellem Jitter auf der x-Achse der übliche DIY-Weg. Für publikationsreife kategoriale Plots (Box, Violin, Swarm) besser Seaborn verwenden, das auf Matplotlib aufbaut und sich in plt-Styling integriert.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(3)
groups = ["A", "B", "C"]
data = [rng.normal(0, 1, 30),
        rng.normal(2, 1, 30),
        rng.normal(1, 1.5, 30)]

for i, d in enumerate(data):
    # add jitter on x so points do not stack on one line
    jitter = rng.uniform(-0.1, 0.1, len(d))
    plt.scatter(np.full(len(d), i) + jitter, d, label=groups[i])

plt.xticks(range(len(groups)), groups)
plt.legend()
plt.show()
04

Balkendiagramme

Vertikales Balkendiagramm

plt.bar(x, height) zeichnet vertikale Balken; x darf Strings sein (kategorial). Der zurückgegebene BarContainer erlaubt es, einzelne Balken zu beschriften oder umzufärben. Die Schleife mit plt.text() beschriftet jeden Balken — passe ha/va ('center'/'bottom') und den y-Versatz an, damit die Labels knapp über dem Balken sitzen.

matplotlib
import matplotlib.pyplot as plt

categories = ["Apple", "Banana", "Cherry", "Date"]
values = [25, 40, 30, 15]

bars = plt.bar(categories, values, color="tab:blue", edgecolor="black")

# annotate each bar with its value
for bar, v in zip(bars, values):
    plt.text(bar.get_x() + bar.get_width()/2, v + 1,
             str(v), ha="center", va="bottom")

plt.title("Fruit Sales")
plt.ylabel("units sold")
plt.ylim(0, 50)
plt.show()

Horizontales Balkendiagramm

plt.barh(y, width) zeichnet horizontale Balken — ideal für lange Kategorie-Labels, die sich in einem vertikalen Diagramm überlappen würden. Rufe ax.invert_yaxis() auf, damit der erste Eintrag oben erscheint, wie man Listen liest. Die Breite ist standardmäßig 0.8.

matplotlib
import matplotlib.pyplot as plt

items = ["Reading", "Coding", "Sleep", "Exercise"]
hours = [2, 6, 8, 1]

plt.barh(items, hours, color="tab:green")
plt.xlabel("hours per day")
plt.title("Daily Activities")

# invert so the first item appears at the top
plt.gca().invert_yaxis()
plt.show()

Gruppiertes Balkendiagramm

Gruppierte Balken platzieren zwei (oder mehr) Reihen nebeneinander, indem die x-Positionen um die halbe Balkenbreite versetzt werden. Das Muster x +/- w/2 mit Breite w setzt sie bündig aneinander. Nutze np.arange für numerische x-Positionen, damit die Rechnung stimmt, und beschrifte danach mit plt.xticks neu.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ["Q1", "Q2", "Q3", "Q4"]
a = [20, 35, 30, 35]
b = [25, 32, 34, 20]
x = np.arange(len(labels))
w = 0.35

plt.bar(x - w/2, a, w, label="2023")
plt.bar(x + w/2, b, w, label="2024")
plt.xticks(x, labels)
plt.ylabel("revenue")
plt.legend()
plt.show()

Gestapeltes Balkendiagramm

Gestapelte Balken nutzen das Argument bottom=: Jede Reihe beginnt dort, wo die vorherige endet. Bei mehr als zwei Reihen akkumulieren: bottom = [m+w for m, w in zip(men, women)]. Gestapelte Balken zeigen Summen und Zusammensetzung, machen aber obere Reihen schwer über Kategorien vergleichbar.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ["A", "B", "C"]
men = [20, 35, 30]
women = [25, 32, 34]

plt.bar(labels, men, label="Men")
plt.bar(labels, women, bottom=men, label="Women")
plt.legend()
plt.title("Stacked Bars")
plt.show()

Balken mit Fehlerbalken

Das Argument yerr fügt vertikale Fehlerbalken hinzu; capsize legt die Länge der Endkappen fest. Mit error_kw stylst du die Balken. Für asymmetrische Fehler übergib yerr=[lower_errors, upper_errors]. Das funktioniert auch bei barh (xerr) und bei plt.errorbar.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ["A", "B", "C"]
means = [20, 35, 30]
errors = [2, 4, 3]

plt.bar(labels, means, yerr=errors, capsize=6,
        color="tab:orange", edgecolor="black",
        error_kw={"ecolor": "black", "linewidth": 1.5})
plt.title("Bar with Error Bars")
plt.ylabel("mean value")
plt.show()
05

Histogramme

Einfaches Histogramm

plt.hist(x) gruppiert die Daten in Bins und zeichnet Balken. bins kann eine Ganzzahl (Anzahl der Bins) oder eine Sequenz expliziter Kanten sein. Standardmäßig werden Häufigkeiten zurückgegeben, die y-Achse zeigt also die Frequenz. Der Rückgabewert ist (counts, bin_edges, patches) und lässt sich weiter anpassen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(0)
data = rng.normal(0, 1, 1000)

plt.hist(data, bins=30)
plt.title("Histogram")
plt.xlabel("value")
plt.ylabel("frequency")
plt.show()

Bins wählen

Die Bin-Wahl verändert das Aussehen eines Histogramms drastisch. 'auto' nutzt das Maximum aus den Sturges- und Freedman-Diaconis-Regeln — ein sinnvoller Standard. Übergib ein explizites Kanten-Array für volle Kontrolle und vergleichbare Bins über Datensätze hinweg. Zu wenige Bins verstecken Struktur; zu viele erzeugen Rauschen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(1)
data = rng.normal(0, 1, 1000)

# auto bin selection (Freedman-Diaconis, Sturges, etc.)
plt.hist(data, bins="auto", alpha=0.5, label="auto")
plt.hist(data, bins=10, alpha=0.5, label="10 bins")
plt.hist(data, bins=np.arange(-4, 4, 0.25),
         alpha=0.5, label="0.25 width")
plt.legend()
plt.show()

Mehrere Histogramme

Überlappende Histogramme brauchen alpha < 1, um beide Verteilungen zu sehen; verwende unterschiedliche Farben. Bei mehr als zwei Gruppen vermeidet stacked=True Unordnung, erschwert aber den Vergleich. Ziehe kdeplot (Seaborn) für glatte Dichtekurven in Betracht, die sich sauberer überlagern lassen als Histogramme.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(2)
a = rng.normal(0, 1, 1000)
b = rng.normal(1, 1.2, 1000)

plt.hist(a, bins=30, alpha=0.6, label="A", color="tab:blue")
plt.hist(b, bins=30, alpha=0.6, label="B", color="tab:orange")
plt.legend()
plt.show()

# stacked alternative
plt.figure()
plt.hist([a, b], bins=30, stacked=True, label=["A", "B"])
plt.legend()
plt.show()

Dichte / Normalisiert

density=True teilt die Häufigkeiten durch (Gesamt * Bin-Breite), sodass die Balkenflächen 1 ergeben — eine Wahrscheinlichkeitsdichte. Das macht Histogramme über verschiedene Stichprobengrößen vergleichbar und erlaubt es, ein theoretisches PDF zu überlagern. Mit weights= gewichtest du einzelne Stichproben.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(3)
data = rng.normal(0, 1, 1000)

# density=True normalizes the area to 1 (PDF)
plt.hist(data, bins=30, density=True, alpha=0.6)

# overlay the theoretical PDF
from scipy.stats import norm
xs = np.linspace(-4, 4, 200)
plt.plot(xs, norm.pdf(xs), "r-", lw=2)
plt.title("Normalized Histogram + PDF")
plt.show()

2D-Histogramm

plt.hist2d gruppiert zwei Variablen in ein 2-D-Gitter und färbt jede Zelle nach Anzahl — der diskrete Verwandte des Scatter für dichte Daten. Für glattere Ausgabe plt.hexbin verwenden (sechseckige Bins). Beide akzeptieren eine cmap und geben Werte zurück, die sich an colorbar übergeben lassen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(4)
x = rng.normal(0, 1, 10000)
y = x + rng.normal(0, 1, 10000)

plt.hist2d(x, y, bins=40, cmap="Blues")
plt.colorbar(label="count")
plt.title("2D Histogram")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
06

Tortendiagramme

Einfaches Tortendiagramm

plt.pie(x, labels) zeichnet eine Torte aus den Werten in x. autopct formatiert die Prozent-Labels (printf-String oder Funktion). startangle dreht den Start des ersten Segments. Immer plt.axis('equal') setzen, damit die Torte ein echter Kreis statt einer Ellipse ist.

matplotlib
import matplotlib.pyplot as plt

labels = ["Rent", "Food", "Transport", "Fun"]
sizes = [1200, 600, 300, 400]

plt.pie(sizes, labels=labels, autopct="%1.1f%%", startangle=90)
plt.title("Monthly Budget")
plt.axis("equal")   # circle, not ellipse
plt.show()

Explode & Schatten

explode ist ein Tupel gleicher Länge wie die Werte; jeder Wert verschiebt das Segment vom Zentrum nach außen (0 = kein Versatz). shadow=True fügt einen Schlagschatten für Tiefe hinzu. Nutze explode sparsam, um ein Segment hervorzuheben — alles herausgezogen wirkt unruhig.

matplotlib
import matplotlib.pyplot as plt

labels = ["A", "B", "C", "D"]
sizes = [30, 25, 25, 20]
explode = (0, 0.1, 0, 0)   # pull the 2nd wedge out

plt.pie(sizes, labels=labels, explode=explode,
        shadow=True, autopct="%1.0f%%",
        startangle=140)
plt.title("Exploded Pie")
plt.show()

Donut-Diagramm

Ein Donut ist einfach eine Torte mit Loch: setze wedgeprops={'width': 0.4}, um Ringe statt voller Segmente zu zeichnen. Das Loch in der Mitte kann über plt.text(0, 0, ...) eine Zusammenfassung aufnehmen. Donuts sind meist leichter lesbar als Torten, weil die Ringlänge Werte besser codiert als der Segmentwinkel.

matplotlib
import matplotlib.pyplot as plt

labels = ["A", "B", "C"]
sizes = [40, 35, 25]

wedges, texts = plt.pie(sizes, labels=labels,
                        wedgeprops=dict(width=0.4, edgecolor="w"))
plt.title("Donut Chart")
# add center text
plt.text(0, 0, "Total\n100", ha="center", va="center", fontsize=14)
plt.show()

Prozent & Startwinkel

autopct darf eine Funktion sein, die den Prozentsatz erhält und einen String zurückgibt — so zeigst du Prozent und absolute Anzahl zugleich. startangle + counterclock=False steuern die Segmentrichtung (oben beginnen, im Uhrzeigersinn — die übliche Lesereihenfolge). pctdistance positioniert die Prozent-Labels.

matplotlib
import matplotlib.pyplot as plt

labels = ["North", "South", "East", "West"]
sizes = [32, 24, 28, 16]
colors = ["#4C72B0", "#DD8452", "#55A868", "#C44E52"]

plt.pie(sizes, labels=labels, colors=colors,
        autopct=lambda p: f"{p:.1f}%\n({p*sum(sizes)/100:.0f})",
        startangle=90, counterclock=False,
        pctdistance=0.75)
plt.show()

Verschachtelte Torte (konzentrisch)

Zwei plt.pie-Aufrufe mit unterschiedlichen radius- und width-Werten erzeugen konzentrische Ringe, ein einfacher 'Sunburst'. Der äußere Ring zeigt typischerweise die Hauptkategorien, der innere deren Aufschlüsselung. Halte den inneren Radius kleiner und setze edgecolor='w', um Segmente visuell zu trennen.

matplotlib
import matplotlib.pyplot as plt

# outer ring: regions, inner ring: sub-categories
outer = [40, 30, 30]
inner = [20, 20, 15, 15, 25, 5]
outer_labels = ["A", "B", "C"]
inner_labels = ["A1", "A2", "B1", "B2", "C1", "C2"]

plt.pie(outer, labels=outer_labels, radius=1.0,
        wedgeprops=dict(width=0.3, edgecolor="w"))
plt.pie(inner, labels=inner_labels, radius=0.7,
        wedgeprops=dict(width=0.3, edgecolor="w"))
plt.title("Nested Pie")
plt.show()
07

Subplots & Layouts

plt.subplot

plt.subplot(rows, cols, index) wählt die (1-basierte) Axes in einem Raster — die klassische MATLAB-Art. Der Index läuft von links nach rechts, von oben nach unten. Er verändert die 'aktuellen Axes', sodass nachfolgende plt-Aufrufe dort zeichnen. Für neuen Code plt.subplots() bevorzugen — sauberer und liefert echte Axes-Objekte.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 50)

# subplot(nrows, ncols, index)  -- 1-indexed!
plt.subplot(2, 2, 1)
plt.plot(x, x)

plt.subplot(2, 2, 2)
plt.plot(x, x**2)

plt.subplot(2, 2, 3)
plt.plot(x, x**3)

plt.subplot(2, 2, 4)
plt.plot(x, np.sin(x))

plt.tight_layout()
plt.show()

plt.subplots

plt.subplots(nrows, ncols) gibt (fig, axes) zurück, wobei axes ein NumPy-Array von Axes ist — indiziere es wie axes[row, col]. sharex/sharey richten Ticks aus und sparen Platz. fig.suptitle() setzt einen titel über alle Subplots. Immer plt.tight_layout() aufrufen, um Label-Überlappungen zu vermeiden.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)

# one figure, 2x2 grid of Axes, shared x and y
fig, axes = plt.subplots(2, 2, figsize=(8, 6),
                         sharex=True, sharey=True)

axes[0, 0].plot(x, np.sin(x)); axes[0, 0].set_title("sin")
axes[0, 1].plot(x, np.cos(x)); axes[0, 1].set_title("cos")
axes[1, 0].plot(x, np.tan(x)); axes[1, 0].set_title("tan")
axes[1, 1].plot(x, -np.sin(x)); axes[1, 1].set_title("-sin")

fig.suptitle("Trig Family")
plt.tight_layout()
plt.show()

GridSpec

GridSpec gibt volle Kontrolle über Subplot-Größen — Zellen lassen sich per Slicing zusammenlegen (gs[0, :] = ganze Zeile, gs[1:, 2] = hohe rechte Spalte). Mit width_ratios/height_ratios erzeugst du ungleiche Spalten/Zeilen. Das Standardwerkzeug für komplexe Dashboards.

matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(3, 3, figure=fig)

ax1 = fig.add_subplot(gs[0, :])     # full top row
ax2 = fig.add_subplot(gs[1, :2])    # middle, left 2 cols
ax3 = fig.add_subplot(gs[1:, 2])    # right, spans 2 rows
ax4 = fig.add_subplot(gs[2, 0:2])   # bottom-left

ax1.set_title("wide top")
ax3.set_title("tall right")
plt.tight_layout()
plt.show()

Achsen teilen

sharex=True (oder sharey=True) koppelt Achsen: Schwenken/Zoomen einer Achse aktualisiert die anderen — ideal für gestapelte Zeitreihen. Zusätzlich werden redundante Tick-Labels auf inneren Achsen versteckt. Die geteilten Gruppen sind über ax.get_shared_x_axes() erreichbar; eine Achse lässt sich zum Entkoppeln aus der Gruppe entfernen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)

ax1.plot(x, np.sin(x))
ax2.plot(x, np.cos(x))

# zooming on one now zooms both
ax1.set_xlim(0, 5)
# decouple later if needed
# ax2.get_shared_x_axes().remove(ax2)

fig.suptitle("Shared x-axis")
plt.show()

Tight Layout & Constrained

tight_layout() passt den Abstand einmalig an, um Label-Überlappung zu verhindern, kennt aber fig.suptitle nicht — übergib rect, um Platz zu reservieren. layout='constrained' (oder fig=Figure(layout='constrained')) ist die moderne Alternative: Es berechnet bei jedem Zeichnen neu, behandelt suptitle und Colorbars korrekt und wird für neuen Code empfohlen.

matplotlib
import matplotlib.pyplot as plt

# tight_layout: simple, adjusts subplot spacing
fig, axes = plt.subplots(2, 2)
for ax in axes.flat:
    ax.set_xlabel("x label")
    ax.set_ylabel("y label")
    ax.set_title("a title")
fig.suptitle("tight_layout")
plt.tight_layout()
# leave room for suptitle
plt.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()

# constrained_layout: recomputes on every draw (more robust)
fig, axes = plt.subplots(2, 2, layout="constrained")
fig.suptitle("constrained_layout")
plt.show()
08

Legenden & Annotationen

Einfache Legende

plt.legend() sammelt die Labels aller gezeichneten Künstler. loc legt die Position innerhalb der Achsen fest ('upper right', 'lower left', 'best', ...). Für eine externe Legende kombiniere bbox_to_anchor=(x, y) (Achsen-Bruchteilkoordinaten) mit loc, um die zugehörige Ecke des Legendenrahmens an diesen Punkt zu heften.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 30)
plt.plot(x, x, label="linear")
plt.plot(x, x**2, label="quadratic")
plt.plot(x, x**3, label="cubic")
plt.legend()
plt.show()

# legend outside the axes
plt.figure()
plt.plot(x, x, label="linear")
plt.plot(x, x**2, label="quadratic")
plt.legend(loc="upper left", bbox_to_anchor=(1, 1))
plt.tight_layout()
plt.show()

Legendenposition & Spalten

ncol ordnet Legendeneinträge in mehreren Spalten an — nützlich bei vielen kurzen Labels. frameon/framealpha/fancybox steuern das Aussehen des Legendenrahmens. title ergibt eine Überschrift. Für randlosen Look frameon=False setzen; wirkt in Publikationen oft aufgeräumter.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 30)
for i in range(1, 6):
    plt.plot(x, x**i, label=f"x^{i}")

plt.legend(loc="upper center", ncol=3, fontsize=9,
           frameon=True, framealpha=0.9,
           title="Powers", title_fontsize=10)
plt.title("Custom Legend")
plt.show()

Punkte annotieren

ax.annotate(text, xy, xytext) platziert Text bei xytext und zeichnet (optional) einen Pfeil zu xy. xy ist standardmäßig in Datenkoordinaten. arrowprops ist ein Dict für das Pfeil-Styling; arrowstyle='->' ist am häufigsten. annotate ist deutlich flexibler als plt.text für Beschriftungen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)

# mark and label the maximum
idx = np.argmax(y)
plt.annotate(f"max = {y[idx]:.2f}",
             xy=(x[idx], y[idx]),        # point to annotate
             xytext=(x[idx]-1, 0.5),     # text position
             arrowprops=dict(arrowstyle="->"))
plt.show()

Annotieren mit Pfeilen

arrowprops stylt die Verbindungslinie: arrowstyle ('->', '-|>', '<->'), Farbe, lw. connectionstyle biegt den Pfeil — 'arc3,rad=0.3' krümmt ihn, 'angle3' macht einen rechten Winkel, 'bar' fügt ein T-Stück hinzu. Damit baust du klare Callouts, die um Daten herumführen, ohne Kurven zu überlappen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 100)
plt.plot(x, x**3 - 3*x)

plt.annotate("local min", xy=(1, -2), xytext=(2, -10),
             arrowprops=dict(arrowstyle="->", color="red",
                             lw=2, connectionstyle="arc3,rad=0.3"))
plt.annotate("local max", xy=(-1, 2), xytext=(-3, 8),
             arrowprops=dict(arrowstyle="-|>", color="blue",
                             connectionstyle="angle3"))
plt.show()

Eigene Legenden-Handles

Wenn die Standardlegende (aus gezeichneten Künstlern) nicht reicht, baue eigene Handles mit Line2D, Patch oder Line2D-ohne-Daten und übergib handles= an legend(). Das ist essenziell für Legenden, die Linien, Patches und Scatter-Marker in einem Schlüssel vereinen.

matplotlib
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Patch

plt.plot([1, 2, 3], [1, 4, 9], "o-", color="tab:blue")
plt.plot([1, 2, 3], [1, 8, 27], "s--", color="tab:orange")

custom = [
    Line2D([0], [0], color="tab:blue", marker="o", label="squared"),
    Line2D([0], [0], color="tab:orange", marker="s", ls="--", label="cubed"),
    Patch(facecolor="gray", label="reference band"),
]
plt.legend(handles=custom)
plt.show()
09

Styles, Farben & rcParams

Eingebaute Styles

plt.style.use(name) wendet einen Preset-Look global an; plt.style.context(name) nur temporär innerhalb eines with-Blocks. Beliebte Styles sind 'ggplot', 'seaborn-v0_8-*', 'bmh', 'fivethirtyeight'. Beachte: Seaborn-Styles wurden in Matplotlib 3.6+ mit dem Suffix '-v0_8' umbenannt.

matplotlib
import matplotlib.pyplot as plt

# list all available styles
print(plt.style.available)

# use a style globally
plt.style.use("seaborn-v0_8-whitegrid")

# or as a context manager (temporary)
with plt.style.context("dark_background"):
    plt.figure()
    plt.plot([1, 2, 3], [1, 4, 9])
    plt.title("dark")
    plt.show()

plt.plot([1, 2, 3], [9, 4, 1])
plt.title("default again")
plt.show()

Colormaps

Colormaps fallen in drei Familien: sequential (viridis, plasma) für geordnete 0..N-Daten, diverging (coolwarm, RdBu) für Daten mit bedeutsamem Mittelpunkt (mit vmin/vmax zentriert auf 0 verwenden) und qualitative (Set2, tab10) für unterscheidbare Kategorien. Bevorzuge perceptuell gleichmäßige Maps wie viridis — farbsicher und drucklesbar.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

# sequential, diverging, qualitative
for cmap in ["viridis", "plasma", "coolwarm", "RdBu", "Set2"]:
    plt.scatter(x, y, c=x, cmap=cmap, label=cmap)
    plt.colorbar(label=cmap)
    plt.title(cmap)
    plt.show()

Eigener Farbzyklus

axes.prop_cycle (ein cycler-Objekt) definiert die Folge der Eigenschaften, die beim Hinzufügen von Linien durchlaufen wird. Du kannst color, linestyle, marker und mehr zyklisch durchlaufen — kombiniere cycler(color=[...]) + cycler(linestyle=[...]), um beides gleichzeitig voranzutreiben. So bekommt jeder Plot eine konsistente, markentreue Palette.

matplotlib
import matplotlib.pyplot as plt
from cycler import cycler

# set the default color cycle for new axes
plt.rcParams["axes.prop_cycle"] = cycler(
    color=["#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00"])

for i in range(1, 6):
    plt.plot([0, 1, 2], [i]*3, label=f"line {i}", lw=4)

plt.legend()
plt.title("Custom Cycle")
plt.show()

rcParams

rcParams ist das zentrale Konfigurationsverzeichnis, das jeden Standardwert steuert — Figure-Größe, DPI, Schriften, Linienbreiten, Grid, savefig-Optionen. Setze Werte einmal am Skriptanfang für konsistente Ausgabe. plt.rcParams.update({...}) setzt mehrere auf einmal. Mit mpl.rcParamsFile oder einer matplotlibrc-Datei werden Standardwerte dauerhaft.

matplotlib
import matplotlib.pyplot as plt
import matplotlib as mpl

# read / set individual parameters
mpl.rcParams["figure.figsize"] = (8, 4)
mpl.rcParams["figure.dpi"] = 100
mpl.rcParams["font.size"] = 12
mpl.rcParams["axes.grid"] = True
mpl.rcParams["axes.grid.which"] = "both"
mpl.rcParams["savefig.bbox"] = "tight"

# update many at once
plt.rcParams.update({
    "axes.titlesize": "large",
    "axes.labelsize": "medium",
    "lines.linewidth": 2,
})

plt.plot([1, 2, 3])
plt.title("Configured Defaults")
plt.show()

Farbformate

matplotlib.colors bietet Konvertierung (to_hex, to_rgb), benannte Farblisten und Colormap-Konstruktion. LinearSegmentedColormap.from_list baut aus wenigen Ankerfarben eine kontinuierliche Colormap. Für kategoriale eigene Maps ListedColormap(['#aaa', '#bbb', ...]). So triffst du Markenpaletten exakt.

matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

# all named colors
print(list(mcolors.CSS4_COLORS)[:5])

# convert between formats
print(mcolors.to_hex((0.1, 0.2, 0.5)))      # #1a3380
print(mcolors.to_rgb("#ff8800"))            # (1.0, 0.533, 0.0)

# make a custom colormap from a list of colors
cmap = mcolors.LinearSegmentedColormap.from_list(
    "rg", ["red", "yellow", "green"])
import numpy as np
plt.imshow(np.linspace(0, 1, 256).reshape(1, -1),
           cmap=cmap, aspect="auto")
plt.title("Custom Colormap")
plt.show()
10

Achseneinstellungen

Grenzen (xlim / ylim)

plt.xlim/plt.ylim (oder ax.set_xlim/ax.set_ylim) legen den sichtbaren Datenbereich fest. Übergibst du None, bleibt diese Grenze automatisch skaliert, z. B. fixiert set_ylim(None, 5) nur den oberen Wert. plt.margins() fügt Polster als Anteil des Datenbereichs hinzu statt fester Grenzen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))

# set explicit limits
plt.xlim(2, 8)
plt.ylim(-1.5, 1.5)

# or autoscale with margin
# plt.margins(x=0.05, y=0.1)

# query current limits
print(plt.xlim())   # (2.0, 8.0)
plt.show()

Ticks

plt.xticks(positions) legt fest, wo Ticks erscheinen; plt.xticks(positions, labels) setzt auch ihren Text. Eine leere Liste versteckt Ticks komplett. Bei numerischen Achsen überlässt man die Tick-Wahl meist dem MaxNLocator und überschreibt nur für kategoriale oder symbolische Achsen (wie Vielfache von pi).

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))

# set tick positions
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])

# set positions AND labels
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
           ["0", "pi/2", "pi", "3pi/2", "2pi"])

# turn off ticks
# plt.xticks([])

plt.show()

Tick-Formatierung

Das ticker-Modul gibt präzise Kontrolle: Locators entscheiden, WO Ticks sitzen (MultipleLocator alle N Einheiten, MaxNLocator bis zu N Ticks, LogLocator für Log-Achsen); Formatters entscheiden den Label-TEXT (FormatStrFormatter im printf-Stil, FuncFormatter als beliebige Funktion). Minor-Locators für feine Gitterlinien verwenden.

matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FuncFormatter

x = np.linspace(0, 5, 100)
plt.plot(x, x**2)

ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(MultipleLocator(0.25))
ax.yaxis.set_major_formatter(FormatStrFormatter("%.0f"))

# format with a function
ax.yaxis.set_major_formatter(
    FuncFormatter(lambda v, p: f"{v/1000:.1f}k"))

plt.show()

Log-Skala

plt.xscale('log') / plt.yscale('log') schaltet eine Achse auf logarithmisch — essenziell für Daten über Größenordnungen hinweg. 'symlog' ist eine Log-Skala mit linearem Bereich nahe null, sodass auch negative Werte darstellbar sind. Mit plt.grid(True, which='both') zeigst du major- und minor- (log-abständige) Gitterlinien.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.logspace(0, 4, 50)   # 10^0 .. 10^4
plt.plot(x, x**2)

# log both axes
plt.xscale("log")
plt.yscale("log")

# symlog: log scale that handles negative/zero values
# plt.yscale("symlog", linthresh=1)

plt.title("Log-Log Plot")
plt.grid(True, which="both", ls="--", alpha=0.5)
plt.show()

Seitenverhältnis & Spines

ax.set_aspect('equal') sorgt für gleiche Skalierung, sodass Kreise kreisförmig bleiben — entscheidend für Geometrie und Karten. Spines sind die Achsen-Randlinien; das Ausblenden von oben/rechts ('Despining') ergibt den modernere, von Seaborn populär gemachte Look. Spines lassen sich auch an beliebige Datenpositionen verschieben, um Kreuzachsen zu bauen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
theta = np.linspace(0, 2*np.pi, 100)
ax.plot(np.cos(theta), np.sin(theta))

# equal data units on x and y (a true circle)
ax.set_aspect("equal")

# hide the top and right spines
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)

# move the remaining spines to the center for a cross-hair
# ax.spines["left"].set_position(("data", 0))
# ax.spines["bottom"].set_position(("data", 0))

plt.show()
11

Text & mathematische Ausdrücke

Text in Axes

ax.text(x, y, s) platziert Text standardmäßig in Datenkoordinaten. Mit transform=ax.transAxes nutzt du Achsen-Bruchteilkoordinaten (0,0 = unten links, 1,1 = oben rechts) — so heftest du Labels in eine Ecke, egal wie der Datenbereich aussieht. ha/va steuern horizontale/vertikale Ausrichtung.

matplotlib
import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1])
# ax.text(x, y, s)  -- x, y in data coords
plt.text(0.5, 0.5, "center of plot", ha="center", va="center",
         fontsize=14, color="red", rotation=30)

# align to axes fraction instead of data coords
plt.text(0.02, 0.98, "top-left", transform=plt.gca().transAxes,
         ha="left", va="top", bbox=dict(boxstyle="round", fc="yellow"))
plt.show()

suptitle & figtext

fig.suptitle() fügt einen Titel über die gesamte Figure hinzu (über allen Subplots); reserviere Platz mit tight_layout(rect=[...]) oder nutze layout='constrained'. fig.text(x, y, s) platziert Text in Figure-Bruchteilkoordinaten (0,0 = unten links der Figure), nützlich für Fußzeilen und Quellenangaben.

matplotlib
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2)
axes[0].plot([1, 2, 3])
axes[1].plot([3, 2, 1])

# figure-level title (above all axes)
fig.suptitle("Main Title", fontsize=16, fontweight="bold")

# arbitrary figure-coordinate text
fig.text(0.5, 0.01, "figure footer text", ha="center", fontsize=9)
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.show()

LaTeX-Mathe (mathtext)

Matplotlib hat eine eingebaute mathtext-Engine: Mathe im LaTeX-Stil in Dollarzeichen ($...$) einschließen und Raw-Strings (r"...") verwenden. Übliche Befehle funktionieren: \frac, \sum, \int, griechische Buchstaben \alpha..\omega, Hochstellung x^2, Tiefstellung x_i. Keine externe LaTeX-Installation nötig. r-Strings nutzen, damit Backslashes Python überleben.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))

# mathtext: enclose LaTeX in dollar signs
plt.title(r"$\sin(x)$ vs $x$")
plt.xlabel(r"$x$ (radians)")
plt.ylabel(r"$\sin(x)$")

# fractions, sums, greek letters
plt.text(2, 0.5, r"$\frac{a}{b} + \sum_{i=1}^{n} x_i^2$")
plt.text(2, -0.5, r"$\alpha, \beta, \gamma, \pi, \infty$")
plt.show()

Text-Eigenschaften

Jedes Textobjekt akzeptiert viele Eigenschaften: fontsize, fontweight ('bold'), fontstyle ('italic'), family ('serif'/'sans-serif'/'monospace'), color und ein bbox-Dict für eine Hintergrundbox. Textobjekte werden zurückgegeben, sodass du sie später ändern kannst (nützlich in Animationen und interaktiven Updates).

matplotlib
import matplotlib.pyplot as plt

t = plt.text(0.5, 0.5, "Styled Text",
             fontsize=18, fontweight="bold",
             fontstyle="italic", family="serif",
             color="darkblue",
             bbox=dict(boxstyle="round,pad=0.5",
                       facecolor="lightyellow", edgecolor="black"))

# animate or update properties later
t.set_fontsize(24)
t.set_color("crimson")

plt.show()

Annotationen (textcoords)

annotate's textcoords steuert, wie xytext interpretiert wird: 'data' (Standard, Dateneinheiten), 'offset points' (Punkte relativ zu xy — ideal, um Labels von einem Punkt wegzuschieben), 'axes fraction' (0-1 innerhalb der Achsen) oder 'figure fraction'. Gemischte Koordinatensysteme halten Callouts beim Zoomen lesbar.

matplotlib
import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])

# xy in data coords, xytext in points OFFSET from xy
plt.annotate("offset text", xy=(2, 4),
             xytext=(15, 15), textcoords="offset points",
             arrowprops=dict(arrowstyle="->"))

# xytext in axes fraction
plt.annotate("axes corner", xy=(2, 4),
             xytext=(0.8, 0.8), textcoords="axes fraction",
             arrowprops=dict(arrowstyle="-|>"))

plt.show()
12

Figures speichern

savefig-Grundlagen

plt.savefig(path) schreibt die aktuelle Figure in eine Datei. Entscheidend: Aufruf VOR plt.show() — show() beendet die Ausgabe und kann die Figure schließen/leeren, danach gespeichert ergibt eine leere Datei. Die Dateiendung bestimmt automatisch das Format (.png, .pdf, .svg, .jpg).

matplotlib
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 2])

# save BEFORE plt.show() -- show() clears the figure
plt.savefig("plot.png")
plt.savefig("plot.pdf")
plt.show()

Formate

Format nach Zweck wählen: PNG für Bildschirm/Web, PDF oder SVG (Vektor) für Druck und Nachbearbeitung, weil sie ohne Pixelierung skalieren, JPG nur für fotähnliche Bilder (verliert Schärfe bei Linien und Text). Vektorformate erzeugen bei elementarmen Plots auch viel kleinere Dateien. Mit format= die Endung überschreiben.

matplotlib
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])

# raster formats (pixels)
plt.savefig("plot.png")          # lossless, default
plt.savefig("plot.jpg", quality=95)
plt.savefig("plot.tiff", dpi=200)

# vector formats (scale without pixelation)
plt.savefig("plot.pdf")          # best for publications
plt.savefig("plot.svg")          # editable in Inkscape/Illustrator

# explicit format override
plt.savefig("plot.dat", format="png")

DPI & Auflösung

DPI (dots per inch) legt die Auflösung der Rasterausgabe fest: Pixelmaße = figsize * dpi. 72-100 DPI genügen für Bildschirme; für Druck sind 300+ DPI erforderlich. Als Vektorformat (PDF/SVG) speichern, um Auflösungsprobleme ganz zu vermeiden. savefig.dpi in rcParams setzen für durchgängig hochauflösende Ausgabe im Skript.

matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([1, 2, 3], [1, 4, 9])

# dpi controls pixel density: width_px = figsize[0] * dpi
plt.savefig("low.png", dpi=72)     #  432 x 288 px
plt.savefig("high.png", dpi=300)   # 1800 x 1200 px

# set a global default DPI
plt.rcParams["savefig.dpi"] = 300
plt.savefig("global.png")

bbox_inches & Pad

Standardmäßig beschneidet savefig auf das Figure-Rechteck, was Labels und Titel am Rand abschneiden kann. bbox_inches='tight' erweitert den gespeicherten Bereich auf alle Künstler, danach fügt pad_inches einen kleinen Rand hinzu. Das will man fast immer — als Standard via rcParams['savefig.bbox']='tight' setzen.

matplotlib
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.title("With Long Title That Might Be Cut Off")

# tight bbox trims whitespace and keeps labels inside
plt.savefig("tight.png", bbox_inches="tight", pad_inches=0.1)

# trim even more aggressively
plt.savefig("tighter.png", bbox_inches="tight", pad_inches=0)

# preview the tight bounding box
# bbox = plt.savefig("x.png", bbox_inches="tight")  # returns a Bbox

Transparent & Facecolor

transparent=True macht den Figure-Hintergrund durchsichtig (PNG-Alphakanal) — ideal, um Plots auf Folien oder Webseiten zu legen. facecolor setzt die gespeicherte Hintergrundfarbe (überschreibt die Bildschirmfarbe). Der Axes-Hintergrund wird separat über ax.set_facecolor() gesteuert. Beides kombiniert erlaubt mehrschichtige Designs.

matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_facecolor("#f0f0f0")

# transparent background (alpha channel)
plt.savefig("transparent.png", transparent=True)

# explicit figure face color
plt.savefig("colored.png", facecolor="lightblue", edgecolor="none")

# control which elements are saved
plt.savefig("full.png", facecolor=fig.get_facecolor())
13

3D-Plotting (mplot3d)

3D-Achsen einrichten

Erzeuge 3D-Achsen mit projection='3d' (entweder über add_subplot oder subplot_kw in subplots). Alle 2-D-Methoden funktionieren, plus z-spezifische (set_zlabel, plot_surface, scatter usw.). 3D kommt über das mplot3d-Toolkit, das in Matplotlib enthalten ist und keine Zusatzinstallation braucht.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
# add a 3D axes via projection
ax = fig.add_subplot(projection="3d")

# or from subplots
# fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title("3D Axes")

plt.show()

3D-Scatter

ax.scatter(x, y, z) auf 3D-Achsen zeichnet Punkte im Raum; die Argumente s und c funktionieren wie beim 2-D-Scatter. fig.colorbar(sc) ergänzt die Farbskala. 3D-Scatter eignet sich gut zum Erkunden von Clustern — aber statische 3D-Plots können Tiefe verbergen: interaktiv drehen oder eine Dimension über Farbe codieren.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(0)
n = 200
x = rng.normal(0, 1, n)
y = rng.normal(0, 1, n)
z = rng.normal(0, 1, n)
c = np.sqrt(x**2 + y**2 + z**2)

fig = plt.figure()
ax = fig.add_subplot(projection="3d")
sc = ax.scatter(x, y, z, c=c, cmap="viridis")
fig.colorbar(sc, label="distance from origin")
ax.set_title("3D Scatter")
plt.show()

3D-Oberfläche

plot_surface(X, Y, Z) zeichnet eine farbige Oberfläche; X, Y, Z müssen 2-D-Arrays gleicher Form sein, erzeugt von np.meshgrid. rstride/cstride steuern, wie viele Gitterpunkte übersprungen werden (kleiner = glatter, aber langsamer). cmap färbt nach Z; Colorbar ergänzen (mit shrink, passend zur 3D-Figure).

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5, 5, 80)
y = np.linspace(-5, 5, 80)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = fig.add_subplot(projection="3d")
surf = ax.plot_surface(X, Y, Z, cmap="coolwarm",
                       rstride=1, cstride=1,
                       linewidth=0, antialiased=True)
fig.colorbar(surf, shrink=0.5, aspect=10)
ax.set_title("3D Surface")
plt.show()

3D-Wireframe & Kontur

plot_wireframe zeichnet nur die Gitterlinien (leichter als eine volle Oberfläche, gut zur Strukturansicht). ax.contourf mit zdir='z' und offset projiziert gefüllte Konturen auf eine Ebene unter der Oberfläche — eine verbreitete '2D-unter-3D'-Visualisierung. Oberfläche + projizierte Konturen ergeben reichhaltige Geländeplots.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 30)
y = np.linspace(-3, 3, 30)
X, Y = np.meshgrid(x, y)
Z = X * np.exp(-X**2 - Y**2)

fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.plot_wireframe(X, Y, Z, color="black", rstride=1, cstride=1)
ax.set_title("Wireframe")

# 3D contour (filled) projected at the bottom
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.contourf(X, Y, Z, zdir="z", offset=-0.5, cmap="viridis")
ax.set_title("3D Contour")
plt.show()

3D-Balken

ax.bar3d(x, y, z, dx, dy, dz) zeichnet rechteckige Balken an Positionen (x, y), beginnend bei Basis z mit Breiten dx, dy und Höhe dz. shade=True ergänzt Licht für 3D-Wirkung. Koordinaten-Arrays mit .ravel() glätten, wenn sie von einem meshgrid stammen. 3D-Balken sind schwer lesbar — wenn möglich gruppierte 2D-Balken bevorzugen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(projection="3d")

x = np.arange(3)
y = np.arange(3)
X, Y = np.meshgrid(x, y)
X, Y = X.ravel(), Y.ravel()
Z = np.zeros_like(X)
dz = np.array([1, 2, 3, 2, 3, 1, 3, 1, 2])

ax.bar3d(X, Y, Z, dx=0.6, dy=0.6, dz=dz,
         shade=True, color="tab:orange")
ax.set_title("3D Bar Chart")
plt.show()
14

Konturplots

Konturlinien

plt.contour(X, Y, Z) zeichnet Isolinien, auf denen Z konstant ist. X, Y stammen aus meshgrid. levels legt die Anzahl (oder exakten Werte) der Konturen fest. plt.clabel(cs) beschriftet jede Linie mit ihrem Wert. Linienkonturen sind präzise, aber spärlich; mit contourf für gefüllte Bereiche kombinieren.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)

# line contours
cs = plt.contour(X, Y, Z, levels=15, colors="black", linewidths=0.8)
plt.clabel(cs, inline=True, fontsize=8)
plt.title("Contour Lines")
plt.colorbar(cs)
plt.show()

Gefüllte Konturen

plt.contourf (beachte das 'f') füllt die Bereiche zwischen Konturstufen mit Farbe und ergibt einen glatten Heatmap-Look. Wie contour braucht es gerasterte X, Y, Z. levels steuert die Auflösung. contourf ist der Standardweg, um 2-D-Skalarfelder wie Temperatur, Höhe oder Wahrscheinlichkeitsdichte zu visualisieren.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2

cf = plt.contourf(X, Y, Z, levels=20, cmap="viridis")
plt.colorbar(cf, label="Z")
plt.title("Filled Contour")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

Konturen beschriften (clabel)

plt.clabel(cs) annotiert Konturlinien mit ihrem Z-Wert; inline=True unterbricht die Linie für das Label. fmt formatiert die Zahl ('%.2f' oder eine Funktion). Mit levels=[...] beschriftest du nur bestimmte Isolinien. Beschriftete Konturen vermitteln exakte Werte ohne Colorbar.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = X * np.exp(-X**2 - Y**2)

cs = plt.contour(X, Y, Z, 10, colors="black")
plt.clabel(cs, inline=True, fontsize=9, fmt="%.2f")
# label only specific levels
# plt.clabel(cs, levels=[-0.1, 0, 0.1])
plt.title("Labeled Contours")
plt.show()

Colorbar

plt.colorbar(mappable) fügt einen Farbschlüssel hinzu — immer den Rückgabewert von contour/imshow/scatter übergeben, damit die Zuordnung bekannt ist. set_label/set_ticks passen ihn an. In Subplots können Colorbars einer Achse Platz stehlen; mit dem Argument ax= oder fig.colorbar(mappable, ax=axes) steuerst du die Platzierung über mehrere Achsen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 100)
y = np.linspace(0, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.cos(Y)

cf = plt.contourf(X, Y, Z, cmap="RdBu")

# basic colorbar
cb = plt.colorbar(cf)
cb.set_label("Z value")
cb.set_ticks([-2, -1, 0, 1, 2])

# place colorbar with specific size and padding
# cb = plt.colorbar(cf, fraction=0.046, pad=0.04)

plt.title("Colorbar Example")
plt.show()

meshgrid & griddata

Contour/contourf brauchen Daten auf einem regelmäßigen Gitter. Für verstreute Stichproben mit scipy.interpolate.griddata auf ein meshgrid interpolieren (Methoden: 'linear', 'nearest', 'cubic'). np.mgrid[...] ist eine praktische Kurzform für meshgrid über einen Bereich. Die Originalpunkte darüber zu plotten zeigt, wo Daten dünn sind.

matplotlib
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata

# scattered (x, y, z) samples
rng = np.random.default_rng(0)
pts = rng.uniform(-2, 2, (200, 2))
z = np.sin(pts[:,0]) * np.cos(pts[:,1])

# build a regular grid
grid_x, grid_y = np.mgrid[-2:2:100j, -2:2:100j]

# interpolate scattered data onto the grid
grid_z = griddata(pts, z, (grid_x, grid_y), method="cubic")

plt.contourf(grid_x, grid_y, grid_z, levels=20, cmap="plasma")
plt.scatter(pts[:,0], pts[:,1], c="white", s=5, alpha=0.5)
plt.colorbar(label="z")
plt.title("Scattered -> Grid -> Contour")
plt.show()
15

Bilddarstellung (imshow)

imshow-Grundlagen

plt.imshow(arr) zeigt ein 2-D-Array als Heatmap oder ein 3-D-Array (H, W, 3) als RGB-Bild. Standardmäßig liegt der Ursprung oben links (origin='upper'), passend zu Bildkonventionen — setze origin='lower' für mathematische Achsen. plt.axis('off') versteckt Ticks für eine saubere Bilddarstellung.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

# a 2D array is shown as a heatmap (color = value)
rng = np.random.default_rng(0)
img = rng.random((10, 10))

plt.imshow(img, cmap="viridis")
plt.colorbar(label="value")
plt.title("imshow of a 2D array")
plt.show()

# a 3D array (H, W, 3 or 4) is shown as an RGB(A) image
rgb = rng.integers(0, 256, (50, 50, 3), dtype=np.uint8)
plt.imshow(rgb)
plt.axis("off")
plt.title("RGB image")
plt.show()

Colormap & Colorbar

extent=[xmin, xmax, ymin, max] bildet Array-Pixel auf Datenkoordinaten ab; ohne es nutzt imshow Pixelindizes. origin='lower' legt Zeile 0 nach unten (mathematische Konvention). aspect='auto' streckt das Bild, um die Achsen zu füllen; der Standard 'equal' erhält quadratische Pixel. Das Bildobjekt an colorbar übergeben.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 200)
y = np.linspace(-3, 3, 200)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2) / (X**2 + Y**2 + 1)

im = plt.imshow(Z, extent=[-3, 3, -3, 3], origin="lower",
                cmap="RdBu", aspect="auto")
cb = plt.colorbar(im)
cb.set_label("intensity")
plt.title("imshow with extent")
plt.show()

Interpolation

interpolation steuert, wie Pixel beim Hochskalieren vermischt werden: 'none'/'nearest' zeigt scharfe Blöcke (gut für rohe Pixeldaten), 'bilinear'/'bicubic' glättet zwischen Pixeln (gut für Heatmaps). Interpolation verändert nur die Darstellung, nicht die Daten. Bei kleinen Arrays will man oft 'nearest', damit einzelne Zellen sichtbar bleiben.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(1)
small = rng.random((5, 5))

methods = ["none", "bilinear", "bicubic", "nearest"]
fig, axes = plt.subplots(1, 4, figsize=(12, 3))
for ax, m in zip(axes, methods):
    ax.imshow(small, interpolation=m, cmap="magma")
    ax.set_title(m)
    ax.axis("off")
plt.tight_layout()
plt.show()

vmin / vmax & norm

vmin/vmax fixieren den auf die Colormap abgebildeten Datenbereich (Ausreißer werden abgeschnitten). Für nichtlineare Abbildungen norm=: LogNorm für Daten über Größenordnungen, TwoSlopeNorm, um eine divergierende Map auf einen bedeutsamen Mittelpunkt zu zentrieren (z. B. 0 bei Anomalien). norm und vmin/vmax schließen sich aus — nur eines übergeben.

matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm, TwoSlopeNorm

rng = np.random.default_rng(2)
Z = rng.random((50, 50)) * 1000 + 1

# clamp the colormap range
plt.imshow(Z, vmin=100, vmax=500, cmap="viridis")
plt.colorbar()
plt.title("clipped range")
plt.show()

# log-scaled colors
plt.imshow(Z, norm=LogNorm(vmin=1, vmax=1001), cmap="plasma")
plt.colorbar()
plt.title("log scale")
plt.show()

# diverging norm centered on a midpoint
# norm = TwoSlopeNorm(vmin=-1, vcenter=0, vmax=1)

Bild aus Datei anzeigen

mpimg.imread lädt ein Bild in ein NumPy-Array (float 0-1 für PNG, 0-255 uint8 für JPEG). plt.imshow zeigt es an; plt.imsave schreibt ein Array zurück auf die Festplatte. RGB-Bilder behalten ihre Farben; für Einkanalbilder cmap='gray' übergeben. Beachte: PIL/pillow ist für nicht-triviale Bildverarbeitung mächtiger.

matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# read an image file into a numpy array
img = mpimg.imread("photo.png")     # shape (H, W, 3) or (H, W, 4)
print(img.shape, img.dtype)

plt.imshow(img)
plt.axis("off")
plt.show()

# save the (possibly modified) array back to a file
# plt.imsave("out.png", img)

# drop the alpha channel if present
if img.shape[-1] == 4:
    img = img[..., :3]
16

Polardiagramme

Polar-Achsen

projection='polar' macht aus einer Achse Polarkoordinaten: x ist der Winkel (theta, Radiant) und y der Radius (r). Alle Standardmethoden funktionieren, wirken aber in (theta, r). Polarplots eignen sich für Richtungsdaten, periodische Funktionen und Rotationssymmetrie. Ticks mit ax.set_thetagrids und ax.set_rgrids setzen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

# create a polar axes via projection
fig = plt.figure()
ax = fig.add_subplot(projection="polar")

# or from subplots
# fig, ax = plt.subplots(subplot_kw={"projection": "polar"})

theta = np.linspace(0, 2*np.pi, 100)
ax.plot(theta, np.sin(2*theta))
plt.show()

Polar-Linienplot

Auf einer polar-Achse zeichnet plot(theta, r) Kurven, bei denen theta der Winkel und r der Radius ist. set_rmax begrenzt den radialen Bereich; set_rticks und set_thetagrids passen radiale/winkelbezogene Tick-Positionen an. Polar-Linienplots zeigen periodische Funktionen sauber — eine Sinuswelle schließt sich zu einer Schleife.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2*np.pi, 200)

fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(theta, 1 + np.cos(theta), label="cardioid")
ax.plot(theta, np.abs(np.sin(2*theta)), label="rose")
ax.set_rmax(2.0)
ax.set_rticks([0.5, 1.0, 1.5])
ax.set_thetagrids([0, 90, 180, 270])
ax.legend(loc="upper right")
plt.show()

Radar-/Spinnendiagramm

Ein Radardiagramm ist ein Polar-Linienplot mit einer Achse pro Kategorie. Der Trick: den ersten Wert/Winkel ans Ende anhängen, damit sich die Kurve zu einer Schleife schließt, und das Innere mit alpha füllen. xticks auf die Kategorie-Winkel setzen und beschriften. Radare vergleichen multivariate Profile, können aber täuschen — sparsam einsetzen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ["Speed", "Power", "Range", "Comfort", "Price"]
values = [8, 7, 6, 5, 9]
N = len(labels)

# close the loop
angles = np.linspace(0, 2*np.pi, N, endpoint=False).tolist()
values += values[:1]
angles += angles[:1]

fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(angles, values, "o-")
ax.fill(angles, values, alpha=0.25)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(labels)
ax.set_title("Radar Chart")
plt.show()

Polar-Balken (Rose)

Ein Rose-Diagramm (Polar-Balken) nutzt ax.bar auf einer polar-Achse — jeder Balken belegt einen Winkelsektor. Nützlich für Richtungshistogramme wie Windrichtung oder Wellenperioden-Verteilungen. Balken nach Radius färben (wie gezeigt) ergibt eine zusätzliche Dimension. bottom= stapelt oder versetzt Balken vom Zentrum weg.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(0)
N = 12
theta = np.linspace(0, 2*np.pi, N, endpoint=False)
widths = 2*np.pi / N
radii = rng.uniform(1, 5, N)

fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
bars = ax.bar(theta, radii, width=widths, bottom=0,
              edgecolor="black")

# color bars by radius
for r, bar in zip(radii, bars):
    bar.set_facecolor(plt.cm.viridis(r / radii.max()))
ax.set_title("Rose Diagram")
plt.show()

Polar-Einstellungen

set_theta_zero_location('N') verlegt 0 Radiant nach oben und set_theta_direction(-1) lässt Winkel im Uhrzeigersinn wachsen — die Kompasskonvention. set_rlabel_position(angle) verschiebt die radialen Tick-Labels an einen beliebigen Winkel, um Datenüberlappung zu vermeiden. Diese Kniffe machen aus einem Mathe-Polarplot ein Richtungs-/Kompassdiagramm.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(np.linspace(0, 2*np.pi, 100), np.linspace(0, 1, 100))

# rotate 0 degrees to the top, go clockwise
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)

# radial limits and ticks
ax.set_rlim(0, 1.2)
ax.set_rticks([0.25, 0.5, 0.75, 1.0])
ax.set_rlabel_position(135)   # move radial labels out of the way

# label directions in degrees
ax.set_thetagrids([0, 90, 180, 270], labels=["E","N","W","S"])
plt.show()
17

Twin-Achsen

twinx (sekundäre Y-Achse)

ax.twinx() erzeugt neue Achsen, die die x-Achse teilen, aber eine eigene y-Achse rechts haben — der Standardweg, um zwei Größen mit verschiedenen Einheiten zu plotten (z. B. Temperatur und Luftfeuchte). Achse und Ticks farblich an die jeweilige Kurve anpassen, damit Leser wissen, welche Skala zu welcher Reihe gehört.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax1 = plt.subplots()
ax1.plot(x, np.sin(x), "b-")
ax1.set_xlabel("x")
ax1.set_ylabel("sin(x)", color="b")
ax1.tick_params(axis="y", labelcolor="b")

# a second axes sharing the same x, with an independent y
ax2 = ax1.twinx()
ax2.plot(x, x*10, "r-")
ax2.set_ylabel("10*x", color="r")
ax2.tick_params(axis="y", labelcolor="r")

plt.title("twinx: two y-scales")
plt.show()

twiny (sekundäre X-Achse)

ax.twiny() ist das horizontale Gegenstück: neue Achsen, die die y-Achse teilen, mit eigener x-Achse oben. Damit zeigt man dieselben Daten gegen zwei x-Skalen (z. B. Meter und Fuß, oder Zeit in Sekunden und Minuten). Derselbe Farbtipp gilt — Achsenfarbe an die Kurve anpassen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

y = np.linspace(0, 10, 50)

fig, ax1 = plt.subplots()
ax1.plot(np.exp(y), y, "g-")
ax1.set_ylabel("y")
ax1.set_xlabel("exp(y)", color="g")

# second axes sharing y, independent x on top
ax2 = ax1.twiny()
ax2.plot(y**2, y, "m-")
ax2.set_xlabel("y^2", color="m")

plt.title("twiny: two x-scales")
plt.show()

Kombiniertes Twin-Diagramm

Bei Twin-Achsen hat jede Axes eine eigene Legende. Um eine gemeinsame Legende zu zeigen, sammle die Line-Handles beider Achsen in einer Liste und rufe ax1.legend(lines, labels) auf. Das ist der idiomatische Weg, einen Schlüssel für ein Diagramm mit doppelter Achse zu behalten, damit Leser beide Reihen auf einen Blick zuordnen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0, 5, 100)
temp_c = 20 + 5*np.sin(t)         # Celsius
humidity = 60 - 5*t               # percent

fig, ax1 = plt.subplots(figsize=(8, 4))

l1, = ax1.plot(t, temp_c, "r-o", label="Temperature (C)")
ax1.set_xlabel("time (s)")
ax1.set_ylabel("Temperature (C)", color="r")
ax1.tick_params(axis="y", labelcolor="r")

ax2 = ax1.twinx()
l2, = ax2.plot(t, humidity, "b-s", label="Humidity (%)")
ax2.set_ylabel("Humidity (%)", color="b")
ax2.tick_params(axis="y", labelcolor="b")

# combine legends from both axes
lines = [l1, l2]
ax1.legend(lines, [l.get_label() for l in lines], loc="upper right")
plt.title("Temperature & Humidity")
plt.show()

Twin-Achsen despinen

Twin-Achsen erzeugen von Natur aus eine doppelte obere Randlinie. Die oberen Spines beider Achsen ausblenden für einen aufgeräumten Look und die linken/rechten Spines passend zur jeweiligen y-Achse einfärben. Kombiniert mit farbigen Tick-Labels zeigt das klar, welche Skala zu welcher Kurve gehört, ohne das Diagramm zu überladen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

ax1.plot(x, np.sin(x), color="tab:blue")
ax2.plot(x, np.cos(x), color="tab:orange")

# remove the top spine so the two axes don't double-border
ax1.spines["top"].set_visible(False)
ax2.spines["top"].set_visible(False)

# color the spines to match their axes
ax1.spines["left"].set_color("tab:blue")
ax2.spines["right"].set_color("tab:orange")

plt.title("Clean Twin Axes")
plt.show()

Twin mit anderen Einheiten

Manchmal braucht man keine zweite gezeichnete Reihe — nur eine zweite Achse mit umgerechneten Einheiten (km/Meilen, °C/°F). twiny() erzeugen, die Grenzen mit set_xlim angleichen, dann xticks/xticklabels manuell auf die umgerechneten Werte setzen. So annotiert man eine Datenreihe mit zwei Einheitensystemen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

km = np.linspace(0, 100, 50)
mile = km * 0.621371

fig, ax1 = plt.subplots()
ax1.plot(km, np.sin(km/10), "tab:purple")
ax1.set_xlabel("distance")
ax1.set_ylabel("signal", color="tab:purple")

ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim())          # align x limits
# relabel the top ticks in miles
new_ticks = np.array([0, 25, 50, 75, 100])
ax2.set_xticks(new_ticks)
ax2.set_xticklabels([f"{m:.0f}" for m in new_ticks*0.621371])
ax2.set_xlabel("miles")
plt.show()
18

Fehlerbalken & gefüllte Bereiche

errorbar

plt.errorbar(x, y, yerr) zeichnet Punkte mit vertikalen Fehlerbalken — der Standard für Experimentaldaten mit Unsicherheit. fmt ist ein Plot-Format-String ('o-' = Marker + Linie). ecolor, elinewidth und capsize stylen die Fehlerbalken. Mit xerr= horizontale Fehler, oder beides für 2-D-Unsicherheiten.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 10)
y = np.exp(-x)
yerr = 0.1 + 0.1*x      # error grows with x

plt.errorbar(x, y, yerr=yerr, fmt="o-", color="tab:blue",
             ecolor="gray", elinewidth=1.5, capsize=4,
             markersize=6, label="exp(-x) +/- err")
plt.legend()
plt.title("Error Bar Plot")
plt.show()

Asymmetrische Fehler

Für asymmetrische Unsicherheiten yerr als 2 x N-Array übergeben: Zeile 0 sind die unteren (nach unten zeigenden) Fehler, Zeile 1 die oberen. Üblich bei schiefen Fehlern (z. B. Poisson-Zählwerte). Dasselbe Muster gilt für xerr bei asymmetrischen horizontalen Unsicherheiten.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = np.array([2, 3, 5, 4, 6])
# separate lower and upper errors (each a 1-D array)
yerr = [[0.5, 1, 0.8, 0.6, 1.2],   # lower
        [1.0, 0.8, 1.5, 1.0, 0.7]]  # upper

plt.errorbar(x, y, yerr=yerr, fmt="s", color="tab:green",
             capsize=5)
plt.title("Asymmetric Error Bars")
plt.show()

# horizontal asymmetric errors work the same way
# xerr = [[...lower...], [...upper...]]

fill_between

fill_between(x, y1, y2) schattiert den Bereich zwischen zwei y-Kurven — ideal für Konfidenzintervalle, Fehlerbänder und Bereiche. where= begrenzt die Füllung auf Stellen, an denen ein boolesches Array True ist (bei sich kreuzenden Kurven interpolate=True verwenden). alpha < 1 hält die zugrunde liegende Kurve durch das Band sichtbar.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)
std = 0.2

plt.plot(x, y, "b-", label="mean")
# shade +/- one standard deviation
plt.fill_between(x, y - std, y + std, color="blue", alpha=0.2,
                 label="+/- 1 std")

# shade only where a condition holds
plt.fill_between(x, y, 0, where=(y > 0), color="green", alpha=0.2,
                 label="y > 0")
plt.legend()
plt.show()

stackplot

plt.stackplot(x, y1, y2, ...) stapelt mehrere Reihen übereinander und zeigt Summen und Zusammensetzung über eine kontinuierliche x-Achse (meist Zeit). Anders als gestapelte Balken ist es für kontinuierliche Daten. Die Gesamthöhe ist die Summe aller Reihen. Unterschiedliche Farben mit alpha verwenden, damit die Grenzen zwischen Schichten klar bleiben.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

years = np.arange(2010, 2021)
a = np.array([10, 12, 14, 15, 17, 18, 20, 22, 23, 25, 27])
b = np.array([ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
c = np.array([ 3,  4,  4,  5,  6,  6,  7,  8,  8,  9, 10])

plt.stackplot(years, a, b, c, labels=["A", "B", "C"],
              colors=["#4C72B0", "#55A868", "#C44E52"], alpha=0.8)
plt.legend(loc="upper left")
plt.title("Stacked Area Chart")
plt.xlabel("year")
plt.ylabel("value")
plt.show()

fill (Polygon)

plt.fill(x, y) schließt und schattiert ein beliebiges Polygon — nützlich, um Bereiche hervorzuheben oder unter einer Kurve zu schattieren. Zum Schattieren unter einer Kurve die x-Werte mit ihrer Umkehrung und die y-Werte mit Nullen zusammenfügen. Für mehrere getrennte gefüllte Bereiche 2-D-Arrays übergeben oder fill wiederholt aufrufen.

matplotlib
import matplotlib.pyplot as plt
import numpy as np

# fill a closed polygon defined by its vertices
x = [0, 1, 1, 0, 0]
y = [0, 0, 1, 1, 0]
plt.fill(x, y, color="tab:cyan", alpha=0.5)

# shade under a curve
xs = np.linspace(0, 2*np.pi, 100)
ys = np.sin(xs)
plt.fill(np.r_[xs, xs[::-1]],
         np.r_[ys, np.zeros_like(ys)],
         color="tab:orange", alpha=0.3)

plt.title("Filled Polygons")
plt.show()
19

Seaborn-Integration

Seaborn-Einführung

Seaborn ist eine hochstufige statistische Plotting-Bibliothek auf Matplotlib-Basis: Sie nimmt pandas-DataFrames an, erledigt Gruppierung/Aggregation und hat hübschere Standardwerte. Jede Seaborn-Funktion gibt eine Matplotlib-Axes (oder Figure) zurück, sodass du mit plt-/ax-Aufrufen weiteranpassen kannst. sns.set_theme() einmal aufrufen, um auf Seaborns Stil zu wechseln.

matplotlib
# install seaborn
pip install seaborn

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Seaborn is built ON matplotlib: any sns plot returns an Axes
# and accepts an ax= argument, so you can mix freely.

sns.set_theme()        # apply seaborn's default style
tips = sns.load_dataset("tips")

ax = sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
ax.set_title("Tips dataset")
plt.show()

Seaborn-Styles

sns.set_style setzt das Achsen-Look (Grid, Hintergrund), set_context skaliert Schriften/Linien für das Ausgabemedium ('paper', 'talk', 'poster'), und set_palette legt den Farbzyklus fest. sns.despine() entfernt die oberen/rechten Spines. Das ergibt in ein bis zwei Zeilen einen polierten Standardlook.

matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

# five built-in themes: darkgrid, whitegrid, dark, white, ticks
sns.set_style("whitegrid")
sns.set_context("notebook")   # paper, notebook, talk, poster

# set the color palette
sns.set_palette("Set2")

import numpy as np
for i in range(4):
    plt.plot(np.arange(10), np.arange(10)+i)
plt.title("Seaborn-styled")
plt.show()

# remove the top/right spines (despine) for a clean look
# sns.despine()

relplot (relational)

sns.relplot ist das Figure-Level-Interface für relationale Plots: kind='scatter' (Standard) oder 'line'. col/row splitten die Daten automatisch in Subplots (Faceting) — deutlich einfacher als manuelle Subplots. Es gibt ein FacetGrid zurück, dessen .fig und .axes den Abstieg zu Matplotlib für Feintuning von Titeln und Layout erlauben.

matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")

# scatter or line, faceted by a categorical variable
g = sns.relplot(data=tips, x="total_bill", y="tip",
                hue="smoker", style="time", col="day",
                kind="scatter", height=3, aspect=1.2)

g.fig.suptitle("Tips by day", y=1.03)
plt.show()

histplot & kdeplot

sns.histplot ist der moderne Ersatz für das veraltete distplot: Es zeichnet Histogramme und kann eine Kerndichteschätzung überlagern (kde=True). stat='density' normalisiert, und common_norm=False hält Gruppen unabhängig normalisiert. sns.kdeplot zeichnet nur die glatte Dichtekurve, nützlich zum Vergleichen von Verteilungen.

matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")

# histogram with an overlaid KDE (density curve)
sns.histplot(data=tips, x="total_bill", bins=20, kde=True,
             hue="time", stat="density", common_norm=False)
plt.title("Histogram + KDE")
plt.show()

# standalone KDE
plt.figure()
sns.kdeplot(data=tips, x="total_bill", hue="time", fill=True)
plt.show()

heatmap

sns.heatmap zeichnet eine farbcodierte Matrix mit optionalen Zellannotationen (annot=True). center=0 mit einer divergierenden cmap (coolwarm) macht positive/negative Korrelationen visuell unterscheidbar. Es umschließt plt.imshow + plt.text + colorbar und erspart viel Boilerplate für Korrelations- und Konfusionsmatrizen.

matplotlib
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# correlation matrix
tips = sns.load_dataset("tips")
num = tips.select_dtypes("number").drop(columns=["size"])
corr = num.corr()

sns.heatmap(corr, annot=True, cmap="coolwarm", center=0,
            vmin=-1, vmax=1, square=True,
            linewidths=0.5, fmt=".2f")
plt.title("Correlation Heatmap")
plt.show()

pairplot & violinplot

sns.pairplot erzeugt ein Raster aus Scatter-Plots für jedes Paar numerischer Spalten, gefärbt nach einer kategorialen hue — der schnellste Weg, Beziehungen in einem neuen Datensatz zu erkunden. sns.violinplot kombiniert einen Boxplot mit einer Dichteschätzung und zeigt die Verteilungsform pro Gruppe. Beides ist darunter reines Matplotlib und weiter anpassbar.

matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")

# scatter matrix: every numeric column vs every other
g = sns.pairplot(iris, hue="species", height=2.5)
g.fig.suptitle("Iris pairplot", y=1.01)
plt.show()

# violin plot: box + kernel density on each side
plt.figure()
sns.violinplot(data=iris, x="species", y="sepal_length",
               inner="quartile")
plt.show()
20

Interaktiv & Animation

Slider-Widget

matplotlib.widgets.Slider ergänzt einen interaktiven Schieberegler. Dafür eine eigene Axes erzeugen (oft unten an der Figure via plt.axes([left, bottom, width, height] in Figure-Bruchteilen)), einen Callback an on_changed hängen und darin die Plot-Daten aktualisieren. fig.canvas.draw_idle() zum Auffrischen aufrufen. Erfordert ein interaktives Backend (nicht Agg).

matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)

x = np.linspace(0, 10, 500)
line, = ax.plot(x, np.sin(x))

# axes for the slider
ax_freq = plt.axes([0.2, 0.1, 0.6, 0.03])
slider = Slider(ax_freq, "freq", 0.1, 5.0, valinit=1.0)

def update(val):
    line.set_ydata(np.sin(slider.val * x))
    fig.canvas.draw_idle()

slider.on_changed(update)
plt.show()

Buttons

matplotlib.widgets.Button ergänzt einen klickbaren Button. Wie der Slider braucht er eine eigene Axes (positioniert in Figure-Bruchteilkoordinaten). Der Callback erhält ein Event-Objekt, das man meist ignoriert. Mehrere Widgets (Slider, Buttons, Checkboxen) kombinieren, um einfache Datenexplorations-Dashboards direkt in Matplotlib zu bauen.

matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
(ln,) = ax.plot(np.random.rand(10))

ax_btn = plt.axes([0.7, 0.05, 0.2, 0.075])
btn = Button(ax_btn, "Resample")

def reshuffle(event):
    ln.set_ydata(np.random.rand(10))
    fig.canvas.draw_idle()

btn.on_clicked(reshuffle)
plt.show()

CheckButtons

CheckButtons rendert eine Liste von Checkboxen. Der Callback erhält den Text des umgeschalteten Labels, daran matchst du und kippst die Sichtbarkeit des jeweiligen Künstlers. Damit können Zuschauer Reihen ein-/ausblenden. Wie bei allen Widgets gilt: interaktives Backend nötig, und das Fenster muss offen bleiben.

matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
import numpy as np

x = np.linspace(0, 5, 200)
l1, = plt.plot(x, np.sin(x), label="sin")
l2, = plt.plot(x, np.cos(x), label="cos")
plt.subplots_adjust(right=0.8)

rax = plt.axes([0.82, 0.4, 0.15, 0.2])
check = CheckButtons(rax, ["sin", "cos"], [True, True])

def toggle(label):
    if label == "sin": l1.set_visible(not l1.get_visible())
    if label == "cos": l2.set_visible(not l2.get_visible())
    plt.draw()

check.on_clicked(toggle)
plt.show()

Cursor & Maus-Events

mpl_connect verknüpft Events (button_press_event, motion_notify_event, key_press_event, scroll_event) mit Callbacks. Das Event-Objekt trägt event.xdata/event.ydata (Datenkoordinaten) und event.inaxes (welche Axes, oder None). Das ist die Basis für eigene Interaktionen — Fadenkreuze, Klick-Annotationen, eigene Zoom-Tools.

matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])

def on_click(event):
    if event.inaxes != ax:
        return
    print(f"clicked at x={event.xdata:.2f} y={event.ydata:.2f}")

def on_move(event):
    if event.inaxes == ax:
        ax.set_title(f"x={event.xdata:.2f}, y={event.ydata:.2f}")
        fig.canvas.draw_idle()

fig.canvas.mpl_connect("button_press_event", on_click)
fig.canvas.mpl_connect("motion_notify_event", on_move)
plt.show()

Animation (FuncAnimation)

FuncAnimation treibt eine Animation an, indem es wiederholt update(frame) aufruft. update muss die geänderten Künstler (als Tupel) zurückgeben, damit blit=True nur diese neu zeichnet und schnell bleibt. interval ist die Verzögerung zwischen Frames in ms. Zum Speichern braucht es einen Writer ('ffmpeg' für mp4, 'pillow' für gif). Das Animationsobjekt (ani) referenziert halten, sonst wird es garbage-collected und stoppt.

matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 200)
line, = ax.plot(x, np.sin(x))

def update(frame):
    line.set_ydata(np.sin(x + frame / 10.0))
    return line,

ani = animation.FuncAnimation(fig, update, frames=100,
                              interval=50, blit=True, repeat=True)
# save to a file (requires ffmpeg or pillow installed)
# ani.save("wave.mp4", writer="ffmpeg")
# ani.save("wave.gif", writer="pillow")
plt.show()

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.