Matplotlib-Funktionen zur Verwaltung von Figuren und Achsen
Matplotlib-Referenzdokumentation
Matplotlib bietet eine Reihe von Funktionen zum Erstellen und Verwalten von Figure- und Axes-Objekten. Alle zugehörigen Funktionen sind unten aufgeführt.
Funktionsliste
| Funktion | Beschreibung | pyplot | Entsprechende Methode |
|---|---|---|---|
| figure() | Eine Figure erstellen oder aktivieren | plt.figure() | - |
| subplots() | Ein Figure- und Axes-Gitter erstellen | plt.subplots() | fig.subplots() |
| subplot() | Einen einzelnen Subplot anhand von Zeilen- und Spaltenindex hinzufügen | plt.subplot() | fig.add_subplot() |
| subplot2grid() | Einen Subplot an einer angegebenen Position im Raster erstellen | plt.subplot2grid() | - |
| subplot_mosaic() | Subplots mit Label-Strings anordnen | plt.subplot_mosaic() | fig.subplot_mosaic() |
| axes() | Ein Axes-Objekt zur aktuellen Figur hinzufügen | plt.axes() | fig.add_axes() |
| gca() | Die aktuellen Axes abrufen | plt.gca() | fig.gca() |
| gcf() | Aktuelle Figure abrufen | plt.gcf() | - |
| sca() | Aktuelle Axes festlegen | plt.sca(ax) | fig.sca(ax) |
| cla() | Aktuelle Axes löschen | plt.cla() | ax.cla() |
| clf() | Aktuelle Figure löschen | plt.clf() | fig.clear() |
| close() | Das Figure-Fenster schließen | plt.close() | - |
| delaxes() | Axes aus einer Figure entfernen | plt.delaxes(ax) | fig.delaxes(ax) |
| fignum_exists() | Prüfen, ob eine Figure-Nummer existiert | plt.fignum_exists(n) | - |
| get_figlabels() | Eine Liste aller Figure-Labels abrufen | plt.get_figlabels() | - |
| get_fignums() | Eine Liste aller Figure-Nummern abrufen | plt.get_fignums() | - |
| twinx() | Eine Zwillings-y-Achse erstellen, die die x-Achse teilt | plt.twinx() | ax.twinx() |
| twiny() | Eine zweite x-Achse erstellen, die die y-Achse teilt | plt.twiny() | ax.twiny() |
Anwendungsbeispiele
Beispiel 1: gca/gcf/sca arbeiten mit der aktuellen Figure
Beispiel
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# Die erste Figure erstellen
plt.figure(1)
plt.plot(x, np.sin(x), label='sin(x)')
# Die zweite Figure erstellen
plt.figure(2)
plt.plot(x, np.cos(x), label='cos(x)')
# Prüfen, ob Abbildung 1 existiert
print(plt.fignum_exists(1)) # True
# Alle Abbildungsnummern abrufen
print(plt.get_fignums()) # [1, 2]
# Zurück zu Abbildung 1 wechseln
plt.figure(1)
ax = plt.gca() # Aktuelle Achsen abrufen
print(ax.get_title())
# Aktuelle Achsen auf eine andere setzen
plt.sca(ax)
plt.title('Gewechselt über sca()')
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
# Die erste Figure erstellen
plt.figure(1)
plt.plot(x, np.sin(x), label='sin(x)')
# Die zweite Figure erstellen
plt.figure(2)
plt.plot(x, np.cos(x), label='cos(x)')
# Prüfen, ob Abbildung 1 existiert
print(plt.fignum_exists(1)) # True
# Alle Abbildungsnummern abrufen
print(plt.get_fignums()) # [1, 2]
# Zurück zu Abbildung 1 wechseln
plt.figure(1)
ax = plt.gca() # Aktuelle Achsen abrufen
print(ax.get_title())
# Aktuelle Achsen auf eine andere setzen
plt.sca(ax)
plt.title('Gewechselt über sca()')
plt.show()
True [1, 2]
Beispiel 2: Erstellen eines ungleichmäßigen Layouts mit subplot2grid
Beispiel
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10, 6), layout='constrained')
# subplot2grid(shape, loc, rowspan, colspan)
# shape=(3,3): ein Gitter aus 3 Zeilen und 3 Spalten
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # Oben erstreckt sich über die gesamte Zeile
ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # Links erstreckt sich vertikal über 2 Zeilen
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2) # Oben rechts erstreckt sich über 2 Spalten
ax4 = plt.subplot2grid((3, 3), (2, 1)) # Rechte Mitte
ax5 = plt.subplot2grid((3, 3), (2, 2)) # Rechts unten
x = np.linspace(0, 10, 50)
ax1.plot(x, np.sin(x))
ax1.set_title('Oben: colspan=3')
ax2.plot(x, np.cos(x), 'orange')
ax2.set_title('Links: rowspan=2')
ax3.bar(['A','B','C'], [3,7,5])
ax3.set_title('Rechts oben: colspan=2')
ax4.text(0.5, 0.5, 'Panel 4', ha='center', va='center')
ax5.text(0.5, 0.5, 'Panel 5', ha='center', va='center')
fig.suptitle('subplot2grid Layout', fontsize=14)
plt.show()
import numpy as np
fig = plt.figure(figsize=(10, 6), layout='constrained')
# subplot2grid(shape, loc, rowspan, colspan)
# shape=(3,3): ein Gitter aus 3 Zeilen und 3 Spalten
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # Oben erstreckt sich über die gesamte Zeile
ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # Links erstreckt sich vertikal über 2 Zeilen
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2) # Oben rechts erstreckt sich über 2 Spalten
ax4 = plt.subplot2grid((3, 3), (2, 1)) # Rechte Mitte
ax5 = plt.subplot2grid((3, 3), (2, 2)) # Rechts unten
x = np.linspace(0, 10, 50)
ax1.plot(x, np.sin(x))
ax1.set_title('Oben: colspan=3')
ax2.plot(x, np.cos(x), 'orange')
ax2.set_title('Links: rowspan=2')
ax3.bar(['A','B','C'], [3,7,5])
ax3.set_title('Rechts oben: colspan=2')
ax4.text(0.5, 0.5, 'Panel 4', ha='center', va='center')
ax5.text(0.5, 0.5, 'Panel 5', ha='center', va='center')
fig.suptitle('subplot2grid Layout', fontsize=14)
plt.show()
Beispiel 3: subplot_mosaic Label-Layout
Beispiel
import matplotlib.pyplot as plt
import numpy as np
layout = """
AAAB
CCDD
"""
fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
layout='constrained')
x = np.linspace(0, 10, 100)
# Subplots über Labelnamen ansprechen
axes['A'].plot(x, np.sin(x))
axes['A'].set_title('A: Oberes breites Panel')
axes['B'].plot(x, np.cos(x), 'orange')
axes['B'].set_title('B: Oben rechts')
axes['C'].bar(['X','Y','Z'], [5, 8, 3], color='steelblue')
axes['C'].set_title('C: Unten links')
axes['D'].hist(np.random.randn(200), bins=20,
color='coral', edgecolor='white')
axes⟦⟧set_title['D'].set_title('D: Unten rechts')
fig.suptitle('subplot_mosaic() mit Label-Zugriff')
plt.show()
import numpy as np
layout = """
AAAB
CCDD
"""
fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
layout='constrained')
x = np.linspace(0, 10, 100)
# Subplots über Labelnamen ansprechen
axes['A'].plot(x, np.sin(x))
axes['A'].set_title('A: Oberes breites Panel')
axes['B'].plot(x, np.cos(x), 'orange')
axes['B'].set_title('B: Oben rechts')
axes['C'].bar(['X','Y','Z'], [5, 8, 3], color='steelblue')
axes['C'].set_title('C: Unten links')
axes['D'].hist(np.random.randn(200), bins=20,
color='coral', edgecolor='white')
axes⟦⟧set_title['D'].set_title('D: Unten rechts')
fig.suptitle('subplot_mosaic() mit Label-Zugriff')
plt.show()
Beispiel 4: twinx/twiny duale Achsen
Beispiel
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots(figsize=(8, 4), layout='constrained')
# Primäre y-Achse (linke Seite)
color = 'tab:blue'
ax1.plot(x, np.sin(x) * 100, color=color1, label='Spannung')
ax1.set_xlabel('Zeit (s)')
ax1.set_ylabel('Spannung (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
# twinx() erzeugt eine zweite y-Achse, die die x-Achse teilt (rechte Seite)
ax2 = ax1.twinx()
color2 = 'tab:red'
ax2.plot(x, np.cos(x) * 40 + 50, color=color2, linestyle='--',
label='Temperatur')
ax2.set_ylabel('Temperatur (°C)', color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
ax1.set_title('Doppelte Y-Achsen mit twinx()')
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots(figsize=(8, 4), layout='constrained')
# Primäre y-Achse (linke Seite)
color = 'tab:blue'
ax1.plot(x, np.sin(x) * 100, color=color1, label='Spannung')
ax1.set_xlabel('Zeit (s)')
ax1.set_ylabel('Spannung (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
# twinx() erzeugt eine zweite y-Achse, die die x-Achse teilt (rechte Seite)
ax2 = ax1.twinx()
color2 = 'tab:red'
ax2.plot(x, np.cos(x) * 40 + 50, color=color2, linestyle='--',
label='Temperatur')
ax2.set_ylabel('Temperatur (°C)', color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
ax1.set_title('Doppelte Y-Achsen mit twinx()')
plt.show()
Beispiel 5: cla/clf/close-Aufräumoperationen
Beispiel
import matplotlib.pyplot as plt
import numpy as np
# Eine Figure erstellen und plotten
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Originaldiagramm')
print('Vor cla():', len(ax.get_lines())) # 1
# cla() löscht den Inhalt der Axes (behält die Axes und Figure)
ax.cla()
print('Nach cla():', len(ax.get_lines())) # 0
# Erneut zeichnen
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('Nach cla() und erneutem Zeichnen')
plt.show()
# clf() löscht die gesamte Figure
plt.clf()
print('Nach clf():', len(fig.get_axes())) # 0
# close() schließt das Figure-Fenster
plt.close('all')
print('Beispiel: Bereinigung abgeschlossen')
import numpy as np
# Eine Figure erstellen und plotten
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Originaldiagramm')
print('Vor cla():', len(ax.get_lines())) # 1
# cla() löscht den Inhalt der Axes (behält die Axes und Figure)
ax.cla()
print('Nach cla():', len(ax.get_lines())) # 0
# Erneut zeichnen
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('Nach cla() und erneutem Zeichnen')
plt.show()
# clf() löscht die gesamte Figure
plt.clf()
print('Nach clf():', len(fig.get_axes())) # 0
# close() schließt das Figure-Fenster
plt.close('all')
print('Beispiel: Bereinigung abgeschlossen')
Andere Erweiterungen