Some TikZ tips
Here I gather some pieces of advice regarding TikZ figures. Some external references for TikZ are of course the official manual which has some great tutorials in it, along an exhaustive documentation of the library. Its chapter I.7 Guidelines on Graphics develops some ideas on general use of graphic elements in scientific writing, and is quite independant from TikZ technicalities. I also recommend checking out Overleaf's introduction to TikZ which contains a lighter introduction to the principles of the library.
Colors
I have a dedicated page that list the colors pre-defined when using TikZ as well as some operations allowed under TikZ's color model.
I usually define my own color scheme, and stick to it along the whole document.
The default TikZ colors tend to be quite kitschy.
Below is the palette that I currently use.
It is available as a colors.tex file that I just import into my main document and which redefines some default colors.
Do not hesitate to use opacity variations of those colors (blue!20
instead of blue
for example).
This is also shown in the different rows in the picture below.
Also do not hesitate to tweak it to your liking, there are a lot of helpful websites out there dedicated to colorscheme design.
Lines and Arrows
The thick
and ultra thick
parameters tend to make things more pleasant to look at.
Another classic one: the default arrows are not very good looking to me, so use a replacement for them. A good list of options is available at this page. I usually go with the following:
\usetikzlibrary{arrows}
\begin{tikzpicture}[>=stealth']
...
\end{tikzpicture}
Externalization
When the amount and the complexity of the figures increase in the document, it
is helpful to externalize their compilation, so that they are not compiled at
each new iteration of the document. You might need to enable shell escaping for
this to (e.g. with latexmk --shell-escape ...
).
\usetikzlibrary{external}
\tikzexternalize[prefix=compiled_figures/] % prefix sets where to store figures
It is sometimes useful to disallow externalization for specific figures.
% this disallows the externalization of the very next TikZ figure
\tikzset{external/export next=false}
\begin{tikzpicture}
...
\end{tikzpicture}
% this disallows externalizations of all figures produced by the todo package
\makeatletter
\renewcommand{\todo}[2][]{\tikzexternaldisable\@todo[#1]{#2}\tikzexternalenable}
\makeatother
It can also be useful to set the name of tikz figures, so that your pre-compiled
figures are easily recognizable. Otherwise you would just get a folder full of
figure-1
, figure-2
and so on.
\tikzsetnextfilename{informative_figure_name}
\begin{tikzpicture}
...
\end{tikzpicture}
Externalization and Overleaf
Also note that Overleaf has some special rules for using locally pre-compiled figures (cf this documentation). Basically, pre-compiled files should start by output-
, so you should set the externalization plugin with something in the spirit of:
\usetikzlibrary{external}
\tikzexternalize[prefix=compiled_figures/output-]
Externalization and Beamer
Beware that using externalization for Beamer document can lead to slow compilations, since many beamer-specific elements will be externalized and will need to be re-externalized when their order change (e.g. when inserting a new frame).
Yunqi Shao pointed out to me a solution to this issue, adapted from this
StackOverflow
answer,
using the only named
option of the external
TikZ library. A useful wrapper
can be written as follows:
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[prefix=build/,only named=true]
\usepackage{tikzscale}
\newcommand{\includetikz}[2][]{%
\tikzsetnextfilename{#2}%
\includegraphics[#1]{tikz/#2.tikz}%
}
Which can be used to include figures stored in a tikz/
folder, as follows:
\includetikz[0.3\textwidth]{figure.tikz}
This will include the figure whose TikZ code is in tikz/figure.tikz
, scale it
accordingly to the provided option (thanks to the tikzscale
package), and name it
so that it is externalized. Beacause Beamer elements are not named, they won't be
externalized and therefore only the heavy figures included with \includetikz
will be externalized.
Programming Aspects — Loops, Variables
Loops & Variables
The content of this section has been somewhat scary for me for quit a long time, before I realized that it conveyed additional ways of being lazy.
I want to talk about for
loops, as well as the use of variables to define quantities.
Using foreach
loops is in reality independant of TikZ (since it relies on
LaTeX features), but works particularly well in conjunction with TikZ. I point
out to the section 88 of the official manual 88. Repeating Things for a
precise overview of the syntax and the possibilities.
The basic syntax to define variables, and to use a foreach statement to produce the following figure is detailled below.
\begin{tikzpicture}
\def \mathvariable {\sigma^2};
\def \colorvariable {blue};
\def \alphatransparency {60};
\def \basewidth {0.1cm};
% iterate on the list {1,2,4,8}
\foreach \x in {1,2,4,8} {
% draw a circle at coordinate (1.5*x, 0) whose radius is x*basewidth
% use the defined color and transparency
\fill[\colorvariable!\alphatransparency] (1.5*\x, 0) circle (\x * \basewidth)
node[below=1cm, black] {$\mathvariable = \x$} ;
}
\end{tikzpicture}
Below is an example that purposingly showcases more intricate aspects of
foreach
loops and variables and generates the following figure.
Click to see the code generating the figure.
\begin{tikzpicture}
% the following is equivalent to defining \col as a counter (see the next loop)
% but this showcases zipped loops
\foreach \color / \col in {
blue/0, darkblue/1, red/2, orange/3, green/4,
palegreen/5, yellow/6, brokenwhite/7, brokengrey/8} {
\foreach \alpha [count=\row] in {100, 97, ..., 30} {
% the step (-3) of the loop is infered from the two first values
% random formula to define an angle for the current point and radius
% see that we can perform computations on variables
\def \angle {180*\row/16 + 30*\col};
\def \radius {0.6*\col};
% define a coordinate (center\color\alpha) (which are expanded to their actual
% value so that we can draw a node it later, and have line from the border
\coordinate (center\color\alpha) at ({\radius*cos(\angle}, {\radius * sin(\angle)});
% draw a filled circle node named (circle\color\alpha) centered
% at (center\color\alpha)
% we define a new node so that lines will leave from the edge of
% the circle and not from its center
\node[circle, fill=\color!\alpha]
(circle\color\alpha) at (center\color\alpha) {};
% make a straight line of dots (to showcase an if statement)
\ifnum \col = \row
\fill[color=\color, xshift=6cm] (0.5*\col, 0) circle (0.2);
\fi
}
}
% this showcases a trick to iterate on couples (i-1,i) using the remember keyword
\foreach \color[remember=\color as \lastcolor (initially blue)] in
{darkblue, red, orange, green, palegreen,
yellow, brokenwhite, brokengrey} {
\foreach \alpha in {100, 97, ..., 30} {
\draw[ultra thick, color=\lastcolor!\alpha]
(circle\lastcolor\alpha) -- (circle\color\alpha);
}
}
\end{tikzpicture}
I recommend using this in conjonction with externalization for rather complex figures.
Mathematical Expressions
As you can see in the above section, we were able to define variables through mathematical expressions, for example as
\def \angle {180*\row/16 + 30*\col};
\def \radius {0.6*\col};
\coordinate (center) at ({\radius*cos(\angle}, {\radius * sin(\angle)});
Those operations are handled by pgfmath
under the hood.
Documentation on those operations is available in section 94 of TikZ's manual (94. Mathematical Operation, under Part VIII. Mathematical and Object-Oriented Engines).
For easy-reference, here are the basic mathematical functions that can be used in such expressions. Individual documentation is available in
94.3 Syntax for Mathematical Expressions: Functions.
abs, acos, add, and, array, asin, atan, atan2, bin, ceil, cos, cosec, cosh, cot, deg, depth, dim, div, divide, e, equal, factorial, false, floor, frac, gcd, greater, height, hex, Hex, int, ifthenelse, iseven, isodd, isprime, less, ln, log10, log2, max, min, mod, Mod, multiply, neg, not, notequal, notgreater, notless, oct, or, pi, pow, rad, rand, random, real, rnd, round, scalar, sec, sign, sin, sinh, sqrt, subtract, tan, tanh, true, veclen, width
Plots
To generate nice plots of data, I recommmend using a combination of matplotlib
and seaborn
, and export them to LaTeX compatible plots using tikzplotlib
. So the whole pipeline essentially goes as follows and allows to obtain high quality figures fully rendered with TikZ and pgfplots. One advantage of it is that you can tweak things like axis title, legend, ticks, etc, from inside your LaTeX document, without the need to go inside the code that generated the plot.
import matplotlib.pyplot as plt
import seaborn
import tikzplotlib
seaborn.set() # applies the seaborn default settings
# you can costumize those settings, e.g. to use the colorscheme of your document
plt.plot(whatever)
tikzplotlib.save("figure.tex", wrap=False) # wrap controls the standaloneness of the tex figure
Graphs
To work with graphs, I recommend using networkX
to manipulate them and
network2tikz
to export them to TikZ with a nice control over the layout, the
format, and so on. Moreover, networkX
provides many standard algorithms and
graph-processing pipelines, making it easy to create complex illustrations.
Scaling
You can handle the size of TikZ figures using the scale
options.
\begin{tikzpicture}[scale=0.6] % you can also directly set xscale and / or yscale
The aforementionned scale
may break a figure with text, or some fixed-size nodes (this is the case when exporting graph with network2tikz
for instance). The following might fix the issue by scaling each and every node. Finding the right amount of scaling for both parameters might require a little bit of tweaking though.
\begin{tikzpicture}[scale=0.6, every node/.style={scale=0.6}]
Beamer Tips
Aspect Ratio
On most modern supports, the default beamer image ratio is not optimal and wastes some space. It is easy to switch to another screen ratio, for instance 16:9 using
\documentclass[aspectratio=169]{beamer}
Slides Template
Teaser. True content coming soon.
A TikZ gallery
This is still a work in progress, there are a lot more figures to come. I will
also make the source code for each figure accessible by clicking on them. The
source code will be provided as a standalone tex file. It should compile as
provided, using the latexmk -pdf source.tex
command. The only requirements
is that it uses the colors.tex
file mentionned earlier,
so make sure to have it accessible from your latex source.
Basic Elements
Coming soon (collection of basic atomic elements to serve as a quick access list).
More Advanced Figures
Figures Made By My Esteemed Colleagues
Here is a collection of figures that colleagues have kindly offered to share here.
Yoann Coudert — Osmont
Here are some images by Yoann Coudert — Osmont.
Amadeus Reinald
Here are some images by Amadeus Reinald.