Python
Python
6
License Creative Commons Attribution 4 Python 3 Cheat Sheet Latest version on :
https://perso.limsi.fr/pointal/python:memento
integer, float, boolean, string, bytes Base Types ◾ ordered sequences, fast index access, repeatable values Container Types
int 783 0 -192 0b010 0o642 0xF3 list [1,5,9] ["x",11,8.9] ["mot"] []
zero binary octal hexa tuple (1,5,9) 11,"y",7.4 ("mot",) ()
float 9.23 0.0 -1.7e-6
-6 Non modifiable values (immutables) ☝ expression with only comas →tuple
bool True False ×10
""
str bytes (ordered sequences of chars / bytes)
str "One\nTwo" Multiline string: b""
escaped new line """X\tY\tZ ◾ key containers, no a priori order, fast key access, each key is unique
'I\'m' 1\t2\t3""" dictionary dict {"key":"value"} dict(a=3,b=4,k="v") {}
escaped ' escaped tab (key/value associations) {1:"one",3:"three",2:"two",3.14:"π"}
bytes b"toto\xfe\775" collection set {"key1","key2"} {1,9,3,0} set()
hexadecimal octal ☝ immutables ☝ keys=hashable values (base types, immutables…) frozenset immutable set empty
yes next
while logical condition: ? Loop Control for var in sequence: …
no finish
statements block break immediate exit statements block
continue next iteration
s = 0 initializations before the loop ☝ else block for normal Go over sequence's values
i = 1 condition with a least one variable value (here i) loop exit. s = "Some text" initializations before the loop
Algo: cnt = 0
KEY IMPORTS
We’ll use shorthand in this cheat sheet Import these to start
arr - A numpy Array object import numpy as np
KEY IMPORTS
We’ll use shorthand in this cheat sheet Import these to start
df - A pandas DataFrame object import pandas as pd
s - A pandas Series object import numpy as np
plot([X], Y, [fmt], …) API ax.set_[xy]scale(scale, …) from matplotlib import ticker import matplotlib.animation as mpla
0.0 0.0
ax.[xy]axis.set_[minor|major]_locator(locator)
Cheat sheet Version 3.7.4 X, Y, fmt, color, marker, linestyle linear log
+ any values + values > 0
2.5 2 0 2 symlog 2.510102101 0logit
- 0
ticker.NullLocator() T = np.linspace(0, 2*np.pi, 100)
S = np.sin(T)
Quick start API scatter(X, Y, …)
X, Y, [s]izes, [c]olors, marker, cmap 0.0
API
0.0
any values 0 < values < 1
ticker.MultipleLocator(0.5)
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
line, = plt.plot(T, S)
import numpy as np
import matplotlib as mpl
2.5 1000100
-
2.5 1
+ 0 1 ticker.FixedLocator([0, 1, 5])
0 1 5
def animate(i):
line.set_ydata(np.sin(T+i/50))
import matplotlib.pyplot as plt bar[h](x, height, …) API
Projections
2 API
ticker.LinearLocator(numticks=3)
0.0 2.5 5.0
anim = mpla.FuncAnimation(
plt.gcf(), animate, interval=5)
x, height, width, bottom, align, color ticker.IndexLocator(base=0.5, offset=0.25)
0.25 0.75 1.25 1.75 2.25 2.75 3.25 3.75 4.25 4.75 plt.show()
subplot(…, projection=p)
ticker.AutoLocator()
X = np.linspace(0, 2*np.pi, 100) p=’polar’ p=’3d’ API 0 1 2 3 4 5
Y = np.cos(X) imshow(Z, …) API
ticker.MaxNLocator(n=4)
Styles API
Z, cmap, interpolation, extent, origin 0.0 1.5 3.0 4.5
fig, ax = plt.subplots() ticker.LogLocator(base=10, numticks=15) plt.style.use(style)
103 104 105 106 107 108 109 1010
ax.plot(X, Y, color=’green’) contour[f]([X], [Y], Z, …) API p=ccrs.Orthographic() API default classic grayscale
1.0
import cartopy.crs as ccrs
1.0 1.0
plt.show() 1.0
0 1 2 3 4 5 6
1.0
0 1 2 3 4 5 6 7
1.0
0 1 2 3 4 5 6
Lines
0.5 0.5 0.5
API
ticker.NullFormatter()
0.0 0.0 0.0
4
Anatomy of a figure linestyle or ls
1.0
0 1 2 3 4 5 6
1.0
0 1 2 3 4 5 6
1.0
0 1 2 3 4 5 6
Title Blue signal quiver([X], [Y], U, V, …) API ticker.FixedFormatter(['zero', 'one', 'two', ]) bmh Solarize_Light2 seaborn-v0_8-notebook
Major tick Red signal X, Y, U, V, C, units, angles zero one two three four five 1.0 1.0 1.0
"-" ":" "--" "-." (0,(0.01,2)) 0.5 0.5 0.5
Line
ticker.ScalarFormatter() Quick reminder
(line plot) Markers API 0 1 2 3 4 5
TEX
2 x, y, text, va, ha, size, weight, transform 0.0 1.0 2.0 3.0 4.0 5.0 ax.set_[xy]lim(vmin, vmax)
'.' 'o' 's' 'P' 'X' '*' 'p' 'D' '<' '>' '^' 'v' ticker.PercentFormatter(xmax=5) ax.set_[xy]label(label)
Y axis label 0% 20% 40% 60% 80% 100%
Markers ax.set_[xy]ticks(ticks, [labels])
(scatter plot)
fill[_between][x](…) API '1' '2' '3' '4' '+' 'x' '|' '_' 4 5 6 7 ax.set_[xy]ticklabels(labels)
1
X, Y1, Y2, color, where Ornaments ax.set_title(title)
'$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $' ax.tick_params(width=10, …)
Spines
markevery ax.legend(…) API ax.set_axis_[on|off]()
Figure Line
10 [0, -1] (25, 5) [0, 25, -1] handles, labels, loc, title, frameon
Axes (line plot)
Advanced plots fig.suptitle(title)
0 title
0 0.25 0.50 0.75 1 1.25 1.50 1.75 2 2.25 2.50 2.75 3 3.25 3.50 3.75 4
Minor tick label
X axis label step(X, Y, [fmt], …) API
Colors API
Legend label
fig.tight_layout()
plt.gcf(), plt.gca()
X axis label X, Y, fmt, color, marker, where handletextpad handle
markerfacecolor (mfc)
1 C0 C1 C2 C3 C4 C5 C6 C7 C8 C9
handlelength mpl.rc(’axes’, linewidth=1, …)
0
’Cn’ Label 1 Label 3 [fig|ax].patch.set_alpha(0)
Subplots layout API 0 b 2 g 4 r 6 c 8 m 10 y 12 k 14 w 16 ’x’
1 DarkRed Firebrick Crimson IndianRed Salmon labelspacing markeredgecolor (mec) text=r’$\frac{-e^{i\pi}}{2^n}$’
boxplot(X, …) API
X, notch, sym, bootstrap, widths 10 (1,0,0) (1,0,0,0.75) (1,0,0,0.5) (1,0,0,0.25)
’name’ Label 2 Label 4
subplot[s](rows, cols, …) API 0 2 4 6 8 10 12 14 16 (R,G,B[,A])
10 #FF0000 borderpad columnspacing numpoints or scatterpoints
fig, axs = plt.subplots(3, 3) 0 2 4 #FF0000BB
6 8 #FF000088
10 12 #FF000044
14 16 ’#RRGGBB[AA]’
10 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 borderaxespad
Keyboard shortcuts API
0 2 4 6 8 10 12 14 16 ’x.y’
0
errorbar(X,Y,xerr,yerr, …) API 0 2 4 6 8 10 12 14 16 ctrl + s Save ctrl + w Close plot
G = gridspec(rows,cols, …) API X, Y, xerr, yerr, fmt ax.colorbar(…) API
ax = G[0, :] Colormaps API mappable, ax, cax, orientation r Reset view f Fullscreen 0/1
f View forward b View back
hist(X, bins, …) API plt.get_cmap(name) p Pan view o Zoom to rect
ax.inset_axes(extent) API X, bins, range, density, weights 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
Uniform x X pan/zoom y Y pan/zoom
viridis g Minor grid 0/1 G Major grid 0/1
violinplot(D, …) API magma
ax.annotate(…) API l X axis log/linear L Y axis log/linear
d=make_axes_locatable(ax) API D, positions, widths, vert plasma
text, xy, xytext, xycoords, textcoords, arrowprops
ax = d.new_horizontal(’10%’) Sequential
barbs([X], [Y], U, V, …) API
Greys
text Ten simple rules READ
YlOrBr xytext xy
X, Y, U, V, C, length, pivot, sizes textcoords xycoords
Wistia 1. Know your audience
Getting help Diverging 2. Identify your message
Spectral 3. Adapt the figure
matplotlib.org eventplot(positions, …) API
4. Captions are not optional
Å
positions, orientation, lineoffsets
coolwarm
Event handling API
H github.com/matplotlib/matplotlib/issues RdGy 5. Do not trust the defaults
ď discourse.matplotlib.org Qualitative fig, ax = plt.subplots() 6. Use color effectively
W stackoverflow.com/questions/tagged/matplotlib hexbin(X, Y, C, …) API
tab10 def on_click(event): 7. Do not mislead the reader
Ż https://gitter.im/matplotlib/matplotlib X, Y, C, gridsize, bins
tab20 print(event) 8. Avoid “chartjunk”
F twitter.com/matplotlib Cyclic fig.canvas.mpl_connect( 9. Message trumps beauty
a Matplotlib users mailing list twilight ’button_press_event’, on_click) 10. Get the right tool
Matplotlib for beginners
Matplotlib is a library for making 2D plots in Python. It is
Z = np.random.uniform(0, 1, (8, 8))
Organize
designed with the philosophy that you should be able to
create simple plots with just a few commands: You can plot several data on the same figure, but you can
ax.contourf(Z) also split a figure in several subplots (named Axes):
1 Initialize
Z = np.random.uniform(0, 1, 4) X = np.linspace(0, 10, 100)
import numpy as np Y1, Y2 = np.sin(X), np.cos(X)
import matplotlib.pyplot as plt ax.pie(Z) ax.plot(X, Y1, X, Y2)