Als erstes: IPython interaktiv machen:
%matplotlib inline
# bei euch: %matplotlib (nur in iPython)
Um mit Matplotlib arbeiten zu können, muss die Bibliothek erst einmal importiert werden. Damit wir nicht so viel tippen müssen geben wir ihr einen kürzeren Namen:
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (10, 8)
plt.rcParams['font.size'] = 16
plt.rcParams['lines.linewidth'] = 2
Außerdem brauchen wir ein paar Funktion aus numpy
, die euch schon bekannt sind
import numpy as np
Ein einfaches Beispiel: $f(x)=x^2$
x = np.linspace(0, 1) # gibt 50 Zahlen in gleichmäßigem Abstand von 0–1
plt.plot(x, x**2)
# Falls nicht interaktiv:
# plt.show()
Anderes Beispiel: $\sin(t)$ mit verschiedenen Stilen. Vorsicht, die Funktionen und $\pi$ sind Bestandteil
von numpy
t = np.linspace(0, 2 * np.pi)
plt.plot(t, np.sin(t))
plt.plot(t, np.sin(t), 'r--')
plt.plot(t, np.sin(t), 'go')
Tabelle mit allen Farben und Styles: matplotlib.axes.Axes.plot
Neue Grenzen mit xlim(a, b)
und ylim(a, b)
plt.plot(t, np.sin(t))
plt.xlim(0, 2 * np.pi)
plt.ylim(-1.2, 1.2)
with plt.xkcd():
plt.title('Axes with labels')
plt.plot(t, np.sin(t))
plt.xlabel('t / s')
plt.ylabel('U / V')
plt.ylim(-1.1, 1.1)
plt.xlim(0, 2 * np.pi)
Achsen-Beschriftungen können mit LaTeX-Code erstellt werden → LaTeX-Kurs in der nächsten Woche.
plt.plot(t, np.sin(t))
plt.xlabel(r'$t / \mathrm{s}$')
plt.ylabel(r'$U / \mathrm{V}$')
plt.plot(t, np.sin(t))
plt.xlabel(r'$t / \mathrm{s}$')
plt.ylabel(r'$U \,/\, \mathrm{V}$') # Spaces sind Geschmacksfrage……
Mehr zu Einheiten gibt es im LaTeX-Kurs.
Legenden für Objekte die ein label
tragen
plt.plot(t, np.sin(t), label=r'$\sin(t)$')
plt.legend()
#plt.legend(loc='lower left')
#plt.legend(loc='best')
Mit grid()
wird ein Gitter erstellt:
plt.plot(t, np.sin(t))
plt.grid()
x, y = np.genfromtxt('example_data.txt', unpack=True)
plt.plot(x, y, 'k.')
t = np.linspace(0, 10)
plt.plot(t, 5 * t, 'r-')
Speichert den folgenden Code in eine Textdatei plot.py
ab.
Öffnet ein Terminal und startet das Programm:
python plot.py
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1)
plt.plot(x, x**2, 'b-')
plt.savefig('plot.pdf')
Mit savefig
speichert man die Abbildung.
In diesem Fall sollte die Datei plot.pdf
erstellt worden sein.
Es gibt viele Ausgabeformate: pdf
, png
, svg
, LaTeX
Natürlich kann man mehrere Linien in einen Plot packen:
x = np.linspace(0, 1)
plt.plot(x, x**2, label=r'$x^2$')
plt.plot(x, x**4)
plt.plot(x, x**6, 'o', label=r'$x^6$')
plt.legend(loc='best')
Es werden nur die Plots in der Legende angezeigt, die ein Label haben.
Man kann auch mehrere Plots in ein Bild packen:
x = np.linspace(0, 2 * np.pi)
# #rows, #columns, plot index = row * (#cols) + col
plt.subplot(2, 1, 1)
plt.plot(x, x**2)
plt.xlim(0, 2 * np.pi)
plt.subplot(2, 1, 2)
plt.plot(x, np.sin(x))
plt.xlim(0, 2 * np.pi)
Dies führt manchmal zu Spacing-Problemen und Teilen die sich überscheneiden, Lösung:
plt.tight_layout()
x = np.linspace(0, 2 * np.pi)
# Anzahl Zeile, Anzahl Spalten, Nummer des Plots
plt.subplot(2, 1, 1)
plt.plot(x, x**2)
plt.xlim(0, 2 * np.pi)
plt.title(r"$f(x)=x^2$")
plt.subplot(2, 1, 2)
plt.plot(x, np.sin(x))
plt.xlim(0, 2 * np.pi)
plt.title(r"$f(x)=\sin(x)$")
plt.tight_layout()
Plot im Plot:
plt.plot(x, x**2)
# Koordinaten relativ zum Plot (0,0) links unten (1,1) rechts oben
plt.axes([0.2, 0.45, 0.3, 0.3])
plt.plot(x, x**3)
Sehr häufig werden im Praktikum Plots mit Fehlerbalken benötigt:
x = np.linspace(0, 2 * np.pi, 10)
errX = 0.4 * np.random.randn(10)
errY = 0.4 * np.random.randn(10)
plt.errorbar(x + errX, x + errY, xerr=0.4, yerr=errY, fmt='o')
Logarithmische (oder auch andere) Skalierung der Achsen ist auch möglich:
x = np.linspace(0, 10)
plt.plot(x, np.exp(-x))
plt.yscale('log')
#plt.xscale('log')
Manchmal braucht man einen Polarplot:
# r = np.linspace(0, 10, 1000)
r = np.linspace(0, 10, 50)
theta = 2 * np.pi * r
plt.polar(theta, r)
Man kann sehr viele Sachen mit Ticks machen…
x = np.linspace(0, 2 * np.pi)
plt.plot(x, np.sin(x))
plt.xlim(0, 2 * np.pi)
# erste Liste: Tick-Positionen, zweite Liste: Tick-Beschriftung
plt.xticks([0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi],
[r"$0$", r"$\frac{1}{4}\tau$", r"$\frac{1}{2}\tau$", r"$\frac{3}{4}\tau$", r"$\tau$"])
plt.title(r"$\tau$ FTW!")
months = ['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
plt.plot(np.arange(12), np.random.rand(12))
plt.xticks(np.arange(12), months, rotation=45, rotation_mode='anchor', ha='right', va='top')
plt.xlim(0, 11)
Sehr häufig braucht man Histogramme.