-
Notifications
You must be signed in to change notification settings - Fork 896
/
handout-tips.tex
255 lines (216 loc) · 8.64 KB
/
handout-tips.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
\documentclass[10pt,landscape,a4paper]{article}
\usepackage[right=10mm, left=10mm, top=10mm, bottom=10mm]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage[rm,light]{roboto}
\usepackage{xcolor}
\usepackage{graphicx}
\graphicspath{{./figures/}}
\usepackage{multicol}
\usepackage{colortbl}
\usepackage{array}
\setlength\parindent{0pt}
\setlength{\tabcolsep}{2pt}
\baselineskip=0pt
\setlength\columnsep{1em}
\definecolor{Gray}{gray}{0.85}
% --- Listing -----------------------------------------------------------------
\usepackage{listings}
\lstset{
frame=tb, framesep=4pt, framerule=0pt,
backgroundcolor=\color{black!5},
basicstyle=\ttfamily\footnotesize,
commentstyle=\ttfamily\color{black!50},
breakatwhitespace=false,
breaklines=true,
extendedchars=true,
keepspaces=true,
language=Python,
rulecolor=\color{black},
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
%
emph = {
plot, scatter, imshow, bar, contourf, pie, subplots, spines,
add_gridspec, add_subplot, set_xscale, set_minor_locator, linestyle,
dash_capstyle, projection, Stroke, Normal, add_axes, label, savefig,
get_cmap, histtype, annotate, set_minor_formatter, tick_params,
fill_betweenx, text, legend, errorbar, boxplot, hist, title, xlabel,
ylabel, suptitle, fraction, pad, set_fontname, get_xticklabels},
emphstyle = {\ttfamily\bfseries}
}
% --- Fonts -------------------------------------------------------------------
\usepackage{fontspec}
\usepackage[babel=true]{microtype}
\defaultfontfeatures{Ligatures = TeX, Mapping = tex-text}
\setsansfont{Roboto} [ Path = fonts/roboto/Roboto-,
Extension = .ttf,
UprightFont = Light,
ItalicFont = LightItalic,
BoldFont = Regular,
BoldItalicFont = Italic ]
\setromanfont{RobotoSlab} [ Path = fonts/roboto-slab/RobotoSlab-,
Extension = .ttf,
UprightFont = Light,
BoldFont = Bold ]
\setmonofont{RobotoMono} [ Path = fonts/roboto-mono/RobotoMono-,
Extension = .ttf,
Scale = 0.90,
UprightFont = Light,
ItalicFont = LightItalic,
BoldFont = Regular,
BoldItalicFont = Italic ]
\renewcommand{\familydefault}{\sfdefault}
% -----------------------------------------------------------------------------
\begin{document}
\thispagestyle{empty}
\section*{\LARGE \rmfamily
Matplotlib \textcolor{orange}{\mdseries tips \& tricks}}
\begin{multicols*}{3}
% -----------------------------------------------------------------------------
\subsection*{\rmfamily Transparency}
Scatter plots can be enhanced by using transparency (alpha) in order
to show area with higher density. Multiple scatter plots can be
used to delineate a frontier.
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
\begin{lstlisting}[belowskip=-\baselineskip]
X = np.random.normal(-1, 1, 500)
Y = np.random.normal(-1, 1, 500)
ax.scatter(X, Y, 50, "0.0", lw=2) # optional
ax.scatter(X, Y, 50, "1.0", lw=0) # optional
ax.scatter(X, Y, 40, "C1", lw=0, alpha=0.1)
\end{lstlisting} &
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-transparency.pdf}}
\end{tabular}
% -----------------------------------------------------------------------------
\subsection*{\rmfamily Rasterization}
If your figure has many graphical elements, such as a huge
scatter, you can rasterize them to save memory and keep other elements
in vector format.
\begin{lstlisting}
X = np.random.normal(-1, 1, 10_000)
Y = np.random.normal(-1, 1, 10_000)
ax.scatter(X, Y, rasterized=True)
fig.savefig("rasterized-figure.pdf", dpi=600)
\end{lstlisting}
% -----------------------------------------------------------------------------
\subsection*{\rmfamily Offline rendering}
Use the Agg backend to render a figure directly in an array.
\begin{lstlisting}
from matplotlib.backends.backend_agg import FigureCanvas
canvas = FigureCanvas(Figure()))
... # draw some stuff
canvas.draw()
Z = np.array(canvas.renderer.buffer_rgba())
\end{lstlisting}
% -----------------------------------------------------------------------------
\subsection*{\rmfamily Range of continuous colors}
You can use colormap to pick from a range of continuous colors.
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
\begin{lstlisting}[belowskip=-\baselineskip]
X = np.random.randn(1000, 4)
cmap = plt.get_cmap("Oranges")
colors = cmap([0.2, 0.4, 0.6, 0.8])
ax.hist(X, 2, histtype='bar', color=colors)
\end{lstlisting} &
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-color-range.pdf}}
\end{tabular}
% -----------------------------------------------------------------------------
\subsection*{\rmfamily Text outline}
Use text outline to make text more visible.
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
\begin{lstlisting}[belowskip=-\baselineskip]
import matplotlib.patheffects as fx
text = ax.text(0.5, 0.1, "Label")
text.set_path_effects([
fx.Stroke(linewidth=3, foreground='1.0'),
fx.Normal()])
\end{lstlisting} &
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-outline.pdf}}
\end{tabular}
% -----------------------------------------------------------------------------
\subsection*{\rmfamily Multiline plot}
You can plot several lines at once using {\em None} as separator.
\begin{lstlisting}
X,Y = [], []
for x in np.linspace(0, 10*np.pi, 100):
X.extend([x, x, None]), Y.extend([0, sin(x), None])
ax.plot(X, Y, "black")
\end{lstlisting}
\includegraphics[width=\linewidth]{tip-multiline.pdf}
% -----------------------------------------------------------------------------
\subsection*{\rmfamily Dotted lines}
To have rounded dotted lines, use a custom {\ttfamily linestyle} and
modify {\ttfamily dash\_capstyle}.
\begin{lstlisting}
ax.plot([0, 1], [0, 0], "C1",
linestyle=(0, (0.01, 1)), dash_capstyle="round")
ax.plot([0, 1], [1, 1], "C1",
linestyle=(0, (0.01, 2)), dash_capstyle="round")
\end{lstlisting}
\includegraphics[width=\linewidth]{tip-dotted.pdf}
% -----------------------------------------------------------------------------
\subsection*{\rmfamily Combining axes}
You can use overlaid axes with different projections.
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
\begin{lstlisting}[belowskip=-\baselineskip]
ax1 = fig.add_axes([0, 0, 1, 1],
label="cartesian")
ax2 = fig.add_axes([0, 0, 1, 1],
label="polar",
projection="polar")
\end{lstlisting} &
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-dual-axis.pdf}}
\end{tabular}
\subsection*{\rmfamily Colorbar adjustment}
You can adjust a colorbar's size when adding it.
\begin{tabular}{@{}m{.754\linewidth}m{.236\linewidth}}
\begin{lstlisting}[belowskip=-\baselineskip]
im = ax.imshow(Z)
cb = plt.colorbar(im,
fraction=0.046, pad=0.04)
cb.set_ticks([])
\end{lstlisting} &
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-colorbar.pdf}}
\end{tabular}
\subsection*{\rmfamily Taking advantage of typography}
You can use a condensed font such as Roboto
Condensed to save space on tick labels.
\begin{lstlisting}
for tick in ax.get_xticklabels(which='both'):
tick.set_fontname("Roboto Condensed")
\end{lstlisting}
\includegraphics[width=\linewidth]{tip-font-family.pdf}
\subsection*{\rmfamily Getting rid of margins}
Once your figure is finished, you can call {\ttfamily tight\_layout()}
to remove white margins. If there are remaining margins, you can use
the {\ttfamily pdfcrop} utility (comes with TeX live).
\subsection*{\rmfamily Hatching}
You can achieve a nice visual effect with thick hatch patterns.
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
\begin{lstlisting}[belowskip=-\baselineskip]
cmap = plt.get_cmap("Oranges")
plt.rcParams['hatch.color'] = cmap(0.2)
plt.rcParams['hatch.linewidth'] = 8
ax.bar(X, Y, color=cmap(0.6), hatch="/")
\end{lstlisting} &
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-hatched.pdf}}
\end{tabular}
\subsection*{\rmfamily Read the documentation}
Matplotlib comes with an extensive documentation explaining the
details of each command and is generally accompanied by examples.
Together with the huge online gallery, this documentation is a
gold-mine.
\vfill
%
{\scriptsize
Matplotlib 3.7.4 handout for tips \& tricks.
Copyright (c) 2021 Matplotlib Development Team.
Released under a CC-BY 4.0 International License.
Supported by NumFOCUS.
\par}
\end{multicols*}
\end{document}