Öffnet ein Terminal (auf Windows: Git-Bash) und gebt ipython
ein
Als erstes: IPython interaktiv machen:
%matplotlib inline
# bei euch: %maplotlib qt
Man kann beliebige Python-Kommandos eingeben.
Um mit Matplotlib arbeiten zu können, muss die Bibliothek erst einmal importiert werden:
from pylab import *
Ein einfaches Beispiel:
x = linspace(0, 1)
plot(x, x**2)
# Falls nicht interaktiv: show()
Anderes Beispiel: \(\sin(t)\)
t = linspace(0, 2 * pi)
plot(t, sin(t))
#plot(t, sin(t), 'r--')
#plot(t, sin(t), 'go')
Tabelle mit allen Farben und Styles: matplotlib.axes.Axes.plot
plot(t, sin(t))
#xlim(0, 2 * pi)
#ylim(-1.2, 1.2)
with xkcd():
plot(t, sin(t))
xlabel('t')
ylabel('sin(t)')
plot(t, sin(t))
xlabel('$t$')
ylabel('$\sin(t)$')
plot(t, sin(t), label=r'$\sin(t)$')
legend()
#legend(loc='lower left')
x
und f(x)
sind einfach nur Datenpunkte:x = array([1, 2, 3, 4])
x
#x**2
#plot(x, x**2, 'ro-')
x, y = loadtxt('example_data.txt', unpack=True)
plot(x, y, 'k.')
t = linspace(0, 10)
plot(t, 5 * t, 'r-')
Speichert den folgenden Code in eine Textdatei plot.py
ab.
Öffnet ein Terminal und startet das Programm:
python2 plot.py
from pylab import *
x = linspace(0, 1)
plot(x, x**2, 'b-')
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 = linspace(0, 1)
plot(x, x**2, label='$x^2$')
plot(x, x**4)
plot(x, x**6, 'o', label='$x^6$')
legend(loc='best')
Es werden nur die Linien in der Legende angezeigt, die einen Label haben.
Man kann auch mehrere Plots in ein Bild packen:
x = linspace(0, 2 * pi)
subplot(1, 2, 1)
plot(x, x**2)
xlim(0, 2 * pi)
subplot(1, 2, 2)
plot(x, sin(x))
xlim(0, 2 * pi)
Plot im Plot:
plot(x, x**2)
axes([0.2, 0.45, 0.3, 0.3])
plot(x, x**3)
Fehlerbalken sind ganz wichtig:
x = linspace(0, 2 * pi, 10)
errX = 0.4 * randn(10)
errY = 0.4 * randn(10)
errorbar(x + errX, x + errY, xerr=0.4, yerr=0.4, fmt='o')
Logarithmische (und auch viele andere) Skalierung der Achsen ist auch möglich:
x = linspace(0, 10)
plot(x, exp(-x))
yscale('log')
#xscale('log')
Manchmal braucht man einen Polarplot:
r = linspace(0, 10, 1000)
#r = linspace(0, 10, 50)
theta = 2 * pi * r
polar(theta, r)
Man kann sehr viele Sachen mit Ticks machen…
x = linspace(0, 2 * pi)
plot(x, sin(x))
xlim(0, 2 * pi)
xticks([0, pi / 2, pi, 3 * pi / 2, 2 * pi], [r"$0$", r"$\frac{\tau}{4}$", r"$\frac{\tau}{2}$", r"$\frac{3\tau}{4}$", r"$\tau$"])
title(r"$\tau$ FTW!")
months = ['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
plot(arange(12), rand(12))
xticks(arange(12), months, rotation=45, rotation_mode='anchor', ha='right', va='top')
xlim(0, 11)
subplot(2, 1, 1)
plot(x, sin(x), 'b-')
xlabel('Test')
xlim(0, 2 * pi)
subplot(2, 1, 2)
plot(x, cos(x), 'r-')
xlim(0, 2 * pi)
tight_layout()