Skip to content

Commit 54b8bc1

Browse files
authored
Merge pull request #14 from matplotlib/nicolas
Nicolas
2 parents fef4b8c + d062ab5 commit 54b8bc1

14 files changed

+539
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
![](./handout-intermediate.png)
1212

13+
![](./handout-tips.png)
14+
1315
# How to compile
1416

1517
1. You need to create a `fonts` repository with:

handout-tips.pdf

75.1 KB
Binary file not shown.

handout-tips.png

434 KB
Loading

handout-tips.tex

+252
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
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, fraction, pad, set_fontname, get_xticklabels},
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 lines, use a 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+
\subsection*{\rmfamily Colorbar adjustment}
192+
You can adjust colorbar aspect when adding it.
193+
194+
\begin{tabular}{@{}m{.754\linewidth}m{.236\linewidth}}
195+
\begin{lstlisting}[belowskip=-\baselineskip]
196+
im = ax.imshow(Z)
197+
198+
cb = plt.colorbar(im,
199+
fraction=0.046, pad=0.04)
200+
cb.set_ticks([])
201+
\end{lstlisting} &
202+
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-colorbar.pdf}}
203+
\end{tabular}
204+
205+
\subsection*{\rmfamily Taking advantage of typography}
206+
You can use a condensed face such as Roboto
207+
Condensed to save space on tick labels.
208+
\begin{lstlisting}
209+
for tick in ax.get_xticklabels(which='both'):
210+
tick.set_fontname("Roboto Condensed")
211+
\end{lstlisting}
212+
\includegraphics[width=\linewidth]{tip-font-family.pdf}
213+
214+
\subsection*{\rmfamily Getting rid of margins}
215+
Once your figure is finished, you can call {\ttfamily tight\_layout()}
216+
to remove white margins. If there are remaining margins, you can use
217+
the {\ttfamily pdfcrop} utility (comes with TeX live).
218+
219+
220+
\subsection*{\rmfamily Hatching}
221+
You can achieve nice visual effect with thick hatch patterns.
222+
223+
\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}}
224+
\begin{lstlisting}[belowskip=-\baselineskip]
225+
cmap = plt.get_cmap("Oranges")
226+
plt.rcParams['hatch.color'] = cmap(0.2)
227+
plt.rcParams['hatch.linewidth'] = 8
228+
ax.bar(X, Y, color=cmap(0.6), hatch="/" )
229+
\end{lstlisting} &
230+
\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-hatched.pdf}}
231+
\end{tabular}
232+
233+
234+
\subsection*{\rmfamily Read the documentation}
235+
236+
Matplotlib comes with an extensive documenation explaining every
237+
detals of each command and is generally accompanied by examples
238+
with. Together with the huge online gallery, this documenation is a
239+
gold-mine.
240+
241+
\vfill
242+
%
243+
{\scriptsize Matplotlib 3.2 handout for tips \& tricks.
244+
Copyright (c) 2020 Nicolas P. Rougier.
245+
Released under a CC-BY 4.0 License.
246+
Supported by NumFocus Grant \#12345.\par}
247+
248+
249+
250+
\end{multicols*}
251+
\end{document}
252+

scripts/tip-color-range.py

+24
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("Oranges")
20+
colors = [cmap(i) for i in [.1,.3,.5,.7]]
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-colorbar.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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.15,2))
13+
mpl.rcParams['axes.linewidth'] = 1.5
14+
d = 0.01
15+
ax = fig.add_axes([d,d,1-2*d,1-2*d], xticks=[], yticks=[])
16+
17+
np.random.seed(1)
18+
Z = np.random.uniform(0,1,(8,8))
19+
cmap = plt.get_cmap("Oranges")
20+
im = ax.imshow(Z, interpolation="nearest", cmap=cmap, vmin=0, vmax=2)
21+
cb = fig.colorbar(im, fraction=0.046, pad=0.04)
22+
cb.set_ticks([])
23+
24+
plt.savefig("../figures/tip-colorbar.pdf")
25+
# plt.show()

scripts/tip-dotted.py

+21
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

+25
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()

0 commit comments

Comments
 (0)