Matplotlib text() / annotate()-Funktion


Matplotlib 参考文档Matplotlib-Referenzdokumentation

text()Text an angegebenen Koordinaten im Diagramm hinzufügen,annotate()Annotationen mit Pfeilen hinzufügen, die präzise auf Datenpunkte zeigen können.

Funktionsdefinition

text()

matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
Axes.text(x, y, s, fontdict=None, **kwargs)

annotate()

matplotlib.pyplot.annotate(text, xy, xytext=None, xycoords='data',
    textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)
Axes.annotate(text, xy, xytext=None, xycoords='data',
    textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)

Parameterbeschreibung

text() Parameter

ParameterBeschreibung
x, yKoordinaten der Textposition
sDie anzuzeigende Zeichenkette
fontsizeSchriftgröße
colorTextfarbe
ha / horizontalalignmentHorizontale Ausrichtung: 'center', 'right', 'left'
va / verticalalignmentVertikale Ausrichtung: 'center', 'top', 'bottom', 'baseline'
rotationRotationswinkel (Grad)
fontweightSchriftstärke: 'normal', 'bold', 'light'
bboxEigenschaften der Text-Hintergrundbox, z. B. dict(facecolor='yellow', alpha=0.5)

annotate()-spezifische Parameter

ParameterBeschreibung
textTextinhalt der Annotation
xyKoordinaten des Zielpunkts, auf den gezeigt wird (x, y) (Pfeilspitze)
xytextKoordinaten für die Position der Textplatzierung. Standard ist None (Text wird an der xy-Position platziert)
xycoords / textcoordsKoordinatensystem von xy / xytext: 'data', 'axes fraction', 'figure fraction', 'offset points', usw.
arrowpropsWörterbuch der Pfeileigenschaften, z. B. dict(arrowstyle='->', color='gray', lw=1.5)

Der Kernwert von annotate besteht darin, dass xy und xytext den Koordinatenpunkt und die Textposition getrennt angeben können und die beiden mit einem Pfeil verbunden werden, was text() nicht kann.

arrowprops Gängige Pfeilstile

StyleWirkung
'->'Ausgefüllter Dreieckspfeil
'-'Keine Linie
'<->'Doppelkopfpfeil
'-[widthB=...,lengthB=...]'Benutzerdefinierter rechteckiger Pfeil
'fancy'Eleganter geschwungener Pfeil
'simple'Einfacher gerader Pfeil

Anwendungsbeispiele

Beispiel 1: Einfaches Hinzufügen von Text (text)

Beispiel

import matplotlib.pyplot as plt
import numpy as np

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

fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')

ax.plot(x, y, 'steelblue', linewidth=2)

# Textbeschriftung an der Spitze hinzufügen
peak_idx = np.argmax(y)
ax.text(x[peak_idx], y[peak_idx] + 0.1,
        f'Spitze: ({x[peak_idx]:.2f}, {y[peak_idx]:.2f})',
        fontsize=10, color='red',
        ha='center', va='bottom',
        fontweight='bold')

# Text + Hintergrundbox am Tal hinzufügen
valley_idx = np.argmin(y)
ax.text(x[valley_idx], y[valley_idx] - 0.15,
        f'Tal: ({x[valley_idx]:.2f}, {y[valley_idx]:.2f})',
        fontsize=10, ha='center', va='top',
        bbox=dict(boxstyle='round,pad=0.3',
                  facecolor='yellow', alpha=0.7))

ax.set_title('text() - Text an bestimmten Koordinaten hinzufügen')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.grid(True, alpha=0.3)
plt.show()

Beispiel 2: Pfeilannotation (annotate)

Beispiel

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 50)
y = np.exp(-x/3) * np.sin(2 * x)  # Gedämpfte Schwingung

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
ax.plot(x, y, 'steelblue', linewidth=2, marker='o', markersize=4)

# Den ersten Peak annotieren (der Pfeil zeigt vom Text zum Datenpunkt)
peak1_idx = np.argmax(y)
ax.annotate('1. Peak',
            xy=(x[peak1_idx], y[peak1_idx]),          # Der Punkt, auf den der Pfeil zeigt
            xytext=(x[peak1_idx] + 1.5, y[peak1_idx] + 0.2),  # Textposition
            arrowprops=dict(arrowstyle='-&gt;',
                            color='red', lw=1.5),
            fontsize=11, color='red', fontweight='bold')

# Den Zerfallsbereich annotieren
ax.annotate('Zerfallsbereich',
            xy=(.7, .3), xycoords='axes fraction',     # Achsenkoordinaten verwenden
            xytext=(0.5, 0.8), textcoords='axes fraction',
            arrowprops=dict(arrowstyle='fancy',
                            color='green',
                            connectionstyle='arc3,rad=0.3'),
            fontsize=11, color='green',
            bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

ax.set_title('annotate() - Annotationen mit Pfeilen')
ax.set_xlabel('Zeit (s)')
ax.set_ylabel('Amplitude')
ax.grid(True, alpha=0.3)
plt.show()

Beispiel 3: Formelannotation und Koordinatensystem

Beispiel

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 4*np.pi, 200)
y1 = np.sin(x)
y2 = np.cos(x)

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
ax.plot(x, y1, 'blue', label='sin(x)')
ax.plot(x, y2, 'red', label='cos(x)')

# Mit einer mathematischen Formel an einer festen Position im Diagramm annotieren
ax.text(0.02, 0.95,
        r'$f(x) = sin(x)$',
        transform=ax.transAxes,    # Verwende Achsen-relative Koordinaten (0-1)
        fontsize=14, color='blue',
        verticalalignment='top',
        bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.5))

ax.text(0.02, 0.82,
        r'$g(x) = cos(x)$',
        transform=ax.transAxes,
        fontsize=14, color='red',
        verticalalignment='top',
        bbox=dict(boxstyle='round', facecolor='lightcoral', alpha=0.5))

ax.set_title(r'Mathematische Formel mit LaTeX: $sum_{i=1}^{n} x_i$')
ax.set_xlabel('x (radians)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
print("Beispiel: mathematische Annotation angezeigt")

FAQ

Was ist der Unterschied zwischen text und annotate?

text()Platziert nur Text an angegebenen Koordinaten, geeignet zum Hinzufügen von Beschriftungen oder Beschreibungen.

annotate()Kann einen Pfeil hinzufügen, der den Text und den Datenpunkt verbindet, geeignet zum präzisen Annotieren von Schlüsselpositionen.

Wie verwendet man mathematische Formeln im Text?

LaTeX-Syntax verwenden:r'$alpha + beta$'Das Präfix r kennzeichnet eine Rohzeichenkette, und der Inhalt in $...$ wird als mathematische Formel dargestellt.

Erfordert, dass LaTeX auf dem System installiert ist, oder verwenden Sie den in Matplotlib integrierten mathtext-Renderer.


Matplotlib 参考文档Matplotlib-Referenzdokumentation

Andere Erweiterungen