Matplotlib

Misc

Skeleton

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = plt.axes()
# ax.plot(x, np.sin(x))
# plt.show()

plt.plot(x, np.sin(x))
plt.show()

Colors

plt.plot(x, np.sin(x - 0.0 * np.pi), color='b') # color='#FFDD44' oder (R, G, B)
# - b: blue
# - g: green
# - r: red
# - c: cyan
# - m: magenta
# - y: yellow
# - k: black
# - w: white

Linestyle

plt.plot(x, x + 0, linestyle='solid')
# - '-'
# - '--'
# - '-.'
# - 'solid'
# - 'dashed'
# - 'dashdot'
# - 'dotted'

Axis

plt.xlim(-1, 7)
plt.ylim(-1.25, 1.25)
plt.axis('tight') # Daten + etwas Rand
plt.axis('equal') # gleiche Skalierung x und y

Label & Co.

plt.title("Curves")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(["sin(x)", "cos(x)"])

# => alternativ:
plt.plot(X, Y, label="sin(x)")
plt.legend()
plt.legend(loc="upper left") => Position explizit vorgeben
Plt.legend(frameon=False) => Legende ohne Kasten
plt.text() => Text einfügen
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
ax.annotate(
    '$cos(\pi / 2)$',                     # Text
    xy=(np.pi / 2.0, 1),                  # x&y Pfeilspitze (von x&y Text)
    xytext=(np.pi / 2.0 - 0.65, 1.5),     # x&y Text
    arrowprops=dict(facecolor='black', shrink=0.05),
)

Plot Types

Plot

=> Doku

plt.plot(x, np.sin(x)) # mit Linien verbunden

Plot

Scatter

=> Doku

plt.scatter(x, y, marker='o') # einzelne Punkte
# Marker:
# - 'o'
# - 'v'
# - '^'
# - '<'
# - '>'
# - '8'
# - '*'

Scatter

plt.scatter(x, y, s=10, alpha=0.3, c=colors) # colors ist Farbliste
plt.colorbar() # bei unterschiedlichen Farben auch Farbskala anzeigen

Colored Scatter

Contour

=> Doku

x = np.arange(-10, 10, 0.01)
y = np.arange(-10, 10, 0.01)
X, Y = np.meshgrid(x, y) # erzeugt Gitter für alle x|y-Kobinationen
plt.contour(X, Y, Z, colors='gray') # Konturplot, Funktionswert für alle X|Y-Kombinationen

Contour

Contourf

=> Doku

plt.contour**f**(X, Y, Z, 20, cmap='RdGy') # mit Fläche und Schema für Farbverlauf
plt.colorbar()

ContourF

Hist

=> Doku tbd

plt.hist(data) # Histogramm, Parameter bins
counts, bin_edges = np.histogram(data, bins=5) # Anzahl Elemente pro Bin + Bin-Grenzen

Hist

Hist2D

=> Doku tbd

plt.hist2d(x, y, bins=50, cmap='Blues') # 2D-Histogramm
cb = plt.colorbar()

Hist2D