Skip to content

Commit d924c41

Browse files
committed
Started handout tips
1 parent 7c43639 commit d924c41

File tree

8 files changed

+375
-0
lines changed

8 files changed

+375
-0
lines changed

handout-tips.tex

Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
\documentclass[10pt,landscape,a4paper]{article}
2+
\usepackage[right=10mm, left=10mm, top=10mm, bottom=10mm]{geometry}
3+
\usepackage[utf8]{inputenc}
4+
\usepackage[T1]{fontenc}
5+
\usepackage[english]{babel}
6+
\usepackage[rm,light]{roboto}
7+
\usepackage{xcolor}
8+
\usepackage{graphicx}
9+
\graphicspath{{./figures/}}
10+
\usepackage{multicol}
11+
\usepackage{colortbl}
12+
\usepackage{array}
13+
\setlength\parindent{0pt}
14+
\setlength{\tabcolsep}{2pt}
15+
\baselineskip=0pt
16+
\setlength\columnsep{1em}
17+
\definecolor{Gray}{gray}{0.85}
18+
19+
% --- Listing -----------------------------------------------------------------
20+
\usepackage{listings}
21+
\lstset{
22+
frame=tb, framesep=4pt, framerule=0pt,
23+
backgroundcolor=\color{black!5},
24+
basicstyle=\ttfamily\footnotesize,
25+
commentstyle=\ttfamily\color{black!50},
26+
breakatwhitespace=false,
27+
breaklines=true,
28+
extendedchars=true,
29+
keepspaces=true,
30+
language=Python,
31+
rulecolor=\color{black},
32+
showspaces=false,
33+
showstringspaces=false,
34+
showtabs=false,
35+
tabsize=2,
36+
%
37+
emph = {
38+
plot, scatter, imshow, bar, contourf, pie, subplots, spines,
39+
add_gridspec, add_subplot, set_xscale, set_minor_locator, linestyle,
40+
dash_capstyle, projection, Stroke, Normal, add_axes, label, savefig,
41+
get_cmap, histtype, annotate, set_minor_formatter, tick_params,
42+
fill_betweenx, text, legend, errorbar, boxplot, hist, title, xlabel,
43+
ylabel, suptitle },
44+
emphstyle = {\ttfamily\bfseries}
45+
}
46+
47+
% --- Fonts -------------------------------------------------------------------
48+
\usepackage{fontspec}
49+
\usepackage[babel=true]{microtype}
50+
\defaultfontfeatures{Ligatures = TeX, Mapping = tex-text}
51+
\setsansfont{Roboto} [ Path = fonts/roboto/Roboto-,
52+
Extension = .ttf,
53+
UprightFont = Light,
54+
ItalicFont = LightItalic,
55+
BoldFont = Regular,
56+
BoldItalicFont = Italic ]
57+
\setromanfont{RobotoSlab} [ Path = fonts/roboto-slab/RobotoSlab-,
58+
Extension = .ttf,
59+
UprightFont = Light,
60+
BoldFont = Bold ]
61+
\setmonofont{RobotoMono} [ Path = fonts/roboto-mono/RobotoMono-,
62+
Extension = .ttf,
63+
Scale = 0.90,
64+
UprightFont = Light,
65+
ItalicFont = LightItalic,
66+
BoldFont = Regular,
67+
BoldItalicFont = Italic ]
68+
\renewcommand{\familydefault}{\sfdefault}
69+
70+
% -----------------------------------------------------------------------------
71+
\begin{document}
72+
\thispagestyle{empty}
73+
74+
\section*{\LARGE \rmfamily
75+
Matplotlib \textcolor{orange}{\mdseries tips \& tricks}}
76+
77+
\begin{multicols*}{3}
78+
79+
80+
% -----------------------------------------------------------------------------
81+
\subsection*{\rmfamily Transparency}
82+
83+
Scatter plots can be enhanced by using transparency (alpha) in order
84+
to show area with higher density and multiple scatter plots can be
85+
used to delineate a frontier.
86+
87+
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
88+
\begin{lstlisting}[belowskip=-\baselineskip]
89+
X = np.random.normal(-1,1,500)
90+
Y = np.random.normal(-1,1,500)
91+
ax.scatter(X, Y, 50, "0.0", lw=2) # optional
92+
ax.scatter(X, Y, 50, "1.0", lw=0) # optional
93+
ax.scatter(X, Y, 40, "C1", lw=0, alpha=0.1)
94+
\end{lstlisting} &
95+
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-transparency.pdf}}
96+
\end{tabular}
97+
98+
% -----------------------------------------------------------------------------
99+
\subsection*{\rmfamily Rasterization}
100+
If your figure is made of a lot graphical elements such as a huge
101+
scatter, you can rasterize them to save memory and keep other elements
102+
in vector format.
103+
\begin{lstlisting}
104+
X = np.random.normal(-1, 1, 10_000)
105+
Y = np.random.normal(-1, 1, 10_000)
106+
ax.scatter(X, Y, rasterized=True)
107+
fig.savefig("rasterized-figure.pdf", dpi=600)
108+
\end{lstlisting}
109+
110+
% -----------------------------------------------------------------------------
111+
\subsection*{\rmfamily Offline rendering}
112+
113+
Use the Agg backend to render a figure directly in an array.
114+
\begin{lstlisting}
115+
from matplotlib.backends.backend_agg import FigureCanvas
116+
canvas = FigureCanvas(Figure()))
117+
... # draw som stuff
118+
canvas.draw()
119+
Z = np.array(canvas.renderer.buffer_rgba())
120+
\end{lstlisting}
121+
122+
% -----------------------------------------------------------------------------
123+
\subsection*{\rmfamily Range of continuous colors}
124+
You can use colormap to pick a range of continuous colors.
125+
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
126+
\begin{lstlisting}[belowskip=-\baselineskip]
127+
X = np.random.randn(1000, 4)
128+
cmap = plt.get_cmap("Blues")
129+
colors = [cmap(i) for in in [.2,.4,.6,.8]]
130+
131+
ax.hist(X, 2, histtype='bar', color=colors)
132+
\end{lstlisting} &
133+
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-color-range.pdf}}
134+
\end{tabular}
135+
136+
% -----------------------------------------------------------------------------
137+
\subsection*{\rmfamily Text outline}
138+
Use text outline to make text more visible.
139+
140+
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
141+
\begin{lstlisting}[belowskip=-\baselineskip]
142+
import matplotlib.patheffects as fx
143+
text = ax.text(0.5, 0.1, "Label")
144+
text.set_path_effects([
145+
fx.Stroke(linewidth=3, foreground='1.0'),
146+
fx.Normal()])
147+
\end{lstlisting} &
148+
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-outline.pdf}}
149+
\end{tabular}
150+
151+
152+
% -----------------------------------------------------------------------------
153+
\subsection*{\rmfamily Multiline plot}
154+
You can plot several lines at once using None as separator.
155+
156+
\begin{lstlisting}
157+
X,Y = [], []
158+
for x in np.linspace(0, 10*np.pi, 100):
159+
X.extend([x, x, None]), Y.extend([0, sin(x), None])
160+
plt.plot(X, Y, "black")
161+
\end{lstlisting}
162+
\includegraphics[width=\linewidth]{tip-multiline.pdf}
163+
164+
% -----------------------------------------------------------------------------
165+
\subsection*{\rmfamily Dotted lines}
166+
To have rounded dotted line, use custom {\ttfamily linestyle} and
167+
modify {\ttfamily dash\_capstyle}.
168+
\begin{lstlisting}
169+
plt.plot([0,1], [0,0], "C1",
170+
linestyle = (0, (0.01, 1)), dash_capstyle="round")
171+
plt.plot([0,1], [1,1], "C1",
172+
linestyle = (0, (0.01, 2)), dash_capstyle="round")
173+
\end{lstlisting}
174+
\includegraphics[width=\linewidth]{tip-dotted.pdf}
175+
176+
% -----------------------------------------------------------------------------
177+
\subsection*{\rmfamily Combining axes}
178+
You can use overlaid axes with different projections.
179+
180+
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
181+
\begin{lstlisting}[belowskip=-\baselineskip]
182+
ax1 = fig.add_axes([0,0,1,1],
183+
label="cartesian")
184+
ax2 = fig.add_axes([0,0,1,1],
185+
label="polar",
186+
projection="polar")
187+
\end{lstlisting} &
188+
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-dual-axis.pdf}}
189+
\end{tabular}
190+
191+
192+
\vfill
193+
%
194+
{\scriptsize Matplotlib 3.2 handout for tips \& tricks.
195+
Copyright (c) 2020 Nicolas P. Rougier.
196+
Released under a CC-BY 4.0 License.
197+
Supported by NumFocus Grant \#12345.\par}
198+
199+
200+
201+
\end{multicols*}
202+
\end{document}
203+

scripts/tip-color-range.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# -----------------------------------------------------------------------------
2+
# Matplotlib cheat sheet
3+
# Released under the BSD License
4+
# -----------------------------------------------------------------------------
5+
6+
# Scripts to generate all the basic plots
7+
import numpy as np
8+
import matplotlib as mpl
9+
import matplotlib.pyplot as plt
10+
11+
fig = plt.figure(figsize=(2,2))
12+
mpl.rcParams['axes.linewidth'] = 1.5
13+
d = 0.01
14+
15+
ax = fig.add_axes([d,d,1-2*d,1-2*d], xticks=[], yticks=[])
16+
17+
X = np.random.seed(1)
18+
X = np.random.randn(1000, 4)
19+
cmap = plt.get_cmap("Blues")
20+
colors = [cmap(i) for i in [.2,.4,.6,.8]]
21+
ax.hist(X, 2, density=True, histtype='bar', color=colors)
22+
23+
plt.savefig("../figures/tip-color-range.pdf")
24+
# plt.show()

scripts/tip-dotted.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# -----------------------------------------------------------------------------
2+
# Matplotlib cheat sheet
3+
# Released under the BSD License
4+
# -----------------------------------------------------------------------------
5+
6+
# Scripts to generate all the basic plots
7+
import numpy as np
8+
import matplotlib as mpl
9+
import matplotlib.pyplot as plt
10+
fig = plt.figure(figsize=(5,.25))
11+
12+
ax = fig.add_axes([0,0,1,1], frameon=False,
13+
xticks=[], yticks=[], xlim=[0,1], ylim=[-.5,1.5])
14+
15+
epsilon=1e-12
16+
plt.plot([0,1], [0,0], "black", clip_on=False, lw=8,
17+
ls=(.5,(epsilon, 1)), dash_capstyle="round")
18+
plt.plot([0,1], [1,1], "black", clip_on=False, lw=8,
19+
ls=(-.5,(epsilon, 2)), dash_capstyle="round")
20+
plt.savefig("../figures/tip-dotted.pdf")
21+
plt.show()

scripts/tip-dual-axis.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import numpy as np
2+
import matplotlib as mpl
3+
import matplotlib.pyplot as plt
4+
mpl.rcParams['axes.linewidth'] = 1.5
5+
6+
7+
fig = plt.figure(figsize=(2,2))
8+
d = 0.01
9+
ax1 = fig.add_axes([d,d,1-2*d,1-2*d], label="cartesian")
10+
ax2 = fig.add_axes([d,d,1-2*d,1-2*d], projection="polar", label="polar")
11+
12+
ax1.set_xticks([]) #np.linspace(0.0, 0.4, 5))
13+
ax1.set_yticks([]) #np.linspace(0.0, 1.0, 11))
14+
15+
ax2.set_rorigin(0)
16+
ax2.set_thetamax(90)
17+
ax2.set_ylim(0.5,1.0)
18+
ax2.set_xticks(np.linspace(0, np.pi/2, 10))
19+
ax2.set_yticks(np.linspace(0.5, 1.0, 5))
20+
21+
ax2.set_xticklabels([])
22+
ax2.set_yticklabels([])
23+
24+
plt.savefig("../figures/tip-dual-axis.pdf")
25+
plt.show()

scripts/tip-multiline.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# ----------------------------------------------------------------------------
2+
# Author: Nicolas P. Rougier
3+
# License: BSD
4+
# ----------------------------------------------------------------------------
5+
import numpy as np
6+
import matplotlib as mpl
7+
import matplotlib.pyplot as plt
8+
mpl.rcParams['axes.linewidth'] = 1.5
9+
10+
fig = plt.figure(figsize=(8,1.5))
11+
dx,dy = 0.0025, 0.01
12+
ax = fig.add_axes([dx, dy, 1-2*dx, 1-2*dy], frameon=False)
13+
X,Y = [], []
14+
for x in np.linspace(0.01, 10*np.pi-0.01, 100):
15+
X.extend([x, x,None])
16+
Y.extend([0, np.sin(x), None])
17+
print(X[:10], Y[:10])
18+
plt.plot(X, Y, "black")
19+
plt.xticks([]), plt.yticks([])
20+
plt.xlim(-0.25, 10*np.pi+.25)
21+
plt.ylim(-1.5, 1.5)
22+
plt.tight_layout()
23+
plt.savefig("../figures/tip-multiline.pdf", dpi=100)
24+
plt.show()

scripts/tip-outline.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# -----------------------------------------------------------------------------
2+
# Matplotlib cheat sheet
3+
# Released under the BSD License
4+
# -----------------------------------------------------------------------------
5+
6+
# Scripts to generate all the basic plots
7+
import numpy as np
8+
import matplotlib as mpl
9+
import matplotlib.pyplot as plt
10+
import matplotlib.patheffects as path_effects
11+
12+
fig = plt.figure(figsize=(2,2))
13+
mpl.rcParams['axes.linewidth'] = 1.5
14+
d = 0.01
15+
16+
ax = fig.add_axes([d,d,1-2*d,1-2*d], xticks=[], yticks=[])
17+
18+
np.random.seed(1)
19+
Z = np.random.uniform(0,1,(8,8))
20+
cmap = plt.get_cmap("Blues")
21+
ax.imshow(Z, interpolation="nearest", cmap=cmap, vmin=0, vmax=1)
22+
23+
text = ax.text(0.5, 0.1, "Label", transform=ax.transAxes,
24+
color=cmap(0.9), size=32, weight="bold", ha="center", va="bottom")
25+
text.set_path_effects([path_effects.Stroke(linewidth=5, foreground='white'),
26+
path_effects.Normal()])
27+
plt.savefig("../figures/tip-outline.pdf")
28+

scripts/tip-post-processing.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
from matplotlib.figure import Figure
4+
from matplotlib.backends.backend_agg import FigureCanvas
5+
from scipy.ndimage import gaussian_filter
6+
7+
# First pass for drop-shadow
8+
fig = Figure(figsize=(6,1.5))
9+
canvas = FigureCanvas(fig)
10+
ax = fig.add_axes([0,0,1,1], frameon=False,
11+
xlim=[0,1], xticks=[], ylim=[0,1], yticks=[])
12+
ax.text(0.5, 0.5, "Matplotlib", transform=ax.transAxes,
13+
ha="center", va="center", size=64, color="black")
14+
canvas.draw()
15+
Z = np.array(canvas.renderer.buffer_rgba())[:,:,0]
16+
Z = gaussian_filter(Z, sigma=9)
17+
18+
# Second pass for text + drop-shadow
19+
fig = plt.figure(figsize=(6,1.5))
20+
ax = fig.add_axes([0,0,1,1], frameon=False,
21+
xlim=[0,1], xticks=[], ylim=[0,1], yticks=[])
22+
ax.imshow(Z, extent=[0,1,0,1], cmap=plt.cm.gray, alpha=0.65, aspect='auto')
23+
ax.text(0.5, 0.5, "Matplotlib", transform=ax.transAxes,
24+
ha="center", va="center", size=64, color="black")
25+
26+
plt.savefig("../figures/tip-post-processing.pdf", dpi=600)
27+
# plt.show()

scripts/tip-transparency.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# -----------------------------------------------------------------------------
2+
# Matplotlib cheat sheet
3+
# Released under the BSD License
4+
# -----------------------------------------------------------------------------
5+
import numpy as np
6+
import matplotlib as mpl
7+
import matplotlib.pyplot as plt
8+
mpl.rc('axes', linewidth=1.5)
9+
10+
fig = plt.figure(figsize=(2, 2), dpi=100)
11+
margin = 0.01
12+
ax = fig.add_axes([margin, margin, 1-2*margin, 1-2*margin])
13+
n = 500
14+
X = np.random.normal(0, 0.25, n)
15+
Y = np.random.normal(0, 0.25, n)
16+
ax.scatter(X, Y, s=50, c="k", lw=2)
17+
ax.scatter(X, Y, s=50, c="w", lw=0)
18+
ax.scatter(X, Y, s=40, c="C1", lw=0, alpha=0.1)
19+
20+
ax.set_xlim([-1, 1]), ax.set_xticks([]),
21+
ax.set_ylim([-1, 1]), ax.set_yticks([])
22+
plt.savefig("../figures/tip-transparency.pdf")
23+
plt.show()

0 commit comments

Comments
 (0)