Slides Python 3
Slides Python 3
Hendrik Speleers
Matplotlib: Python Plotting
●
Overview
– Anatomy of a figure
●
Figures and axes
– 2D plotting
●
Standard line plotting
●
Other plotting + text annotation
– 3D plotting
●
3D axes + 3D line/surface plotting
– Other plotting
●
Contours + image visualization
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Matplotlib
– Mathematical plotting library
– Python extension for graphics
●
Suited for visualization of data and creation of high-quality figures
●
Extensive package for 2D plotting, and add-on toolkits for 3D plotting
●
Pyplot: MATLAB-like procedural interface to the object-oriented API
– Import convention
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Matplotlib
– Mathematical plotting library
– Interactive matplotlib sessions
●
IPython console
%matplotlib
●
Jupyter notebook
%matplotlib inline
%matplotlib notebook
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
A simple plot
– Syntax is array-based
...: plt.show()
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
A simple plot
– Default settings (see also plt.rcParams)
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Anatomy
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Anatomy
– Hierarchical structure
– Figure
●
The overall window on which everything is drawn
●
Components: one or more axes, suptitle, ...
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Anatomy
– Axes
●
The area on which the data is plotted
● Belongs to a figure, placed arbitrarily (axes) or in grid (subplot)
●
Components: x/y-axis, ticks, spines, labels, title, legend, ...
●
All methods of active axes are directly callable via Pyplot interface
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Anatomy
– Axes components
● Get or set limits: plt.xlim, plt.ylim, plt.axis
– left, right = plt.xlim()
– plt.xlim(left, right)
– plt.axis((left, right, bottom, top)), plt.axis('equal')
● Get or set ticks: plt.xticks, plt.yticks
– locs, labels = plt.xticks()
– plt.xticks(np.arange(3), ('a', 'b', 'c'))
● Set labels: plt.xlabel(txt), plt.ylabel(txt)
● Set title: plt.title(txt)
● Others: plt.box(), plt.grid(), ...
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Anatomy
– Example
In [1]: plt.figure(facecolor='silver')
...: plt.subplot(1, 2, 1)
...: plt.title('subplot')
...: plt.axes((0.4, 0.3, 0.4, 0.4))
...: plt.xlim(1, 5)
...: plt.ylim(-5, -1)
...: plt.title('axes')
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Standard line plotting: basic syntax
plt.plot(y)
plt.plot(x, y)
plt.plot(x, y, 'clm')
●
Connect data points (x, y) with optional format string
● Color (c): b, g, r, c, m, y, k, w
● Linestyle (l): -, --, -., :
● Marker (m): o, *, ., +, x, s, d, ^, <, >, p, h, ...
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Standard line plotting: advanced syntax
plt.plot(x, y, **kwargs)
**kwargs: color, linestyle, linewidth, marker,
markeredgecolor, markeredgewidth,
markerfacecolor, markersize, label, ...
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– For full plot details, check out plt.plot?
– Example
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Plotting methods are actually connected to axes
●
Pyplot provides an interface to the active axes
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Example: data statistics
●
Data in the file “populations.txt” describes the populations of
hares, lynxes and carrots in northern Canada during 20 years
●
Load the data and plot it
●
Compute the mean populations over time
●
Which species has the highest population each year?
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Example: data statistics
●
Load the data and plot it
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Example: data statistics
●
Compute the mean populations over time
●
Which species has the highest population each year?
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Other plotting
● Log plots: plt.loglog(x, y), plt.semilogx(x, y), plt.semilogy(x, y)
● Polar plots: plt.polar(theta, r)
● Scatter plots: plt.scatter(x, y)
● Bar graphs: plt.bar(x, height), plt.barh(y, width)
● Pie charts: plt.pie(x)
● Histogram: plt.hist(x, bins=None)
● Filled curves: plt.fill(x, y), plt.fill_between(x, y1, y2=0)
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Example
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
2D plotting
– Text
● Axes text: plt.title(txt), plt.xlabel(txt), plt.ylabel(txt)
● Plain text: plt.text(x, y, txt)
● Annotation: plt.annotate(txt, xy=(x, y), xytext=(xt, yt),
arrowprops={'arrowstyle':'->'})
●
Extensive math rendering engine
– Support for TeX markup inside dollar signs ($)
– Use raw strings (precede the quotes with an 'r')
●
2D plotting
– Example
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
3D plotting
– Module mplot3d
●
This toolkit adds simple 3D plotting to matplotlib with same “look-and-feel”
●
It supplies an axes object that can create a 2D projection of a 3D scene
●
3D plotting
– 3D axes properties
● Z-axis: ax.set(..., zlabel='z', zticks=(-1,0,1))
● Orientation: ax.view_init(elev=30, azim=45)
In [1]: ax = plt.axes(projection='3d')
...: ax.view_init(elev=30, azim=45)
...: ax.set(xlabel='x', ylabel='y', zlabel='z')
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
3D plotting
– Natural plot extensions
● Line plots: ax.plot(x, y, z), ax.plot3D(x, y, z)
● Scatter plots: ax.scatter(x, y, z), ax.scatter3D(x, y, z)
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
3D plotting
– Surface plotting
● Wireframe plot: ax.plot_wireframe(X, Y, Z)
● Surface plot: ax.plot_surface(X, Y, Z)
– Surface options
●
Create coordinate matrices from coordinate vectors
– X, Y = np.meshgrid(x, y, sparse=False, copy=True)
●
Color maps: mapping between numeric values and colors
– Use keyword cmap
– Manipulated via module matplotlib.cm
– Examples: jet, hot, coolwarm, bone, ...
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
3D plotting
– Example
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Contour plotting
– Contour lines: basic syntax
plt.contour(Z)
plt.contour(X, Y, Z)
plt.contour(X, Y, Z, levels)
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Contour plotting
– Example
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Image plotting
– Image
●
A matrix of color intensities (via color map)
●
A matrix of RGB or RGBA colors (3D array of dept = 3 or 4)
plt.imshow(img)
●
Image plotting
– Example
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Image plotting
– Example: Mandelbrot set
●
Fractal set of complex numbers
● Definition: any c for which zi+1 = zi2 + c does
not diverge, starting from z0 = 0
● Property: limi→∞ sup | zi+1 | ≤ 2 for any valid c
●
Image plotting
– Example: Mandelbrot set
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Colors
– Predefined colors
●
abbreviation: b, g, r, c, m, y, k, w
●
full name: blue, green, red, cyan, magenta, yellow, black, white, ...
– RGB/RGBA code
●
tuple of three or four float values in [0, 1]
●
a hexadecimal RGB or RGBA string
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Colormaps
Lab Calc
2023-2024
Matplotlib: Python Plotting
●
Input and output
– Save figures
●
Most backends support png, pdf, eps, svg
– Image I/O
Lab Calc
2023-2024