Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท TikZ and Graphics

TikZ Loops, Styles and Libraries

Repeat drawing with \foreach, define reusable TikZ styles, compute points with the calc library, and use decorations, shadows, layers and external caching.

Once you draw more than a handful of shapes you start repeating yourself. TikZ offers three tools against repetition: loops (\foreach) to repeat commands, styles to reuse option sets, and calculations to derive coordinates from others. This lesson also introduces useful libraries and tips for keeping compile times short.

\foreach loops

LATEX
\foreach \i in {0,1,2,3,4}
  \draw (\i,0) circle (0.3);

\foreach \x in {0,0.5,...,3}            % ... lets TikZ infer the step
  \draw (\x,0) -- (\x,0.2);

\foreach \x/\label in {0/zero, 1/one, 2/two}   % several variables
  \node at (\x,1) {\label};

\foreach \i in {1,...,4} {
  \foreach \j in {1,...,4}
    \fill[gray!\the\numexpr\i*\j*6\relax] (\i,\j) rectangle +(0.9,0.9);
}

The loop variable is a macro that starts with a backslash. For a range use {1,...,10}; for a computed list use \foreach \a in {0,30,...,330}. Inside a loop you can use \x in math with \pgfmathparse, or write {\x*2} with curly braces inside coordinates so that TikZ evaluates the expression:

LATEX
\foreach \a in {0,45,...,315}
  \draw (0,0) -- ({2*cos(\a)}, {2*sin(\a)});   % spokes of a circle

TikZ trigonometric functions use degrees by default.

The stand-in below prints the coordinates such a loop produces, which is a quick way to check your expressions before compiling.

JS Compute loop coordinates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Styles

A style names a set of options:

LATEX
\tikzset{
  important/.style = {red, very thick},
  box/.style       = {draw, rounded corners, minimum width=2cm, fill=blue!10},
  arrow/.style     = {->, >=Stealth, thick},
  label/.style     = {font=\footnotesize\itshape, inner sep=2pt},
  myline/.style n args={2}{#1, line width=#2},   % style with parameters
  every node/.style = {font=\small},             % applies to every node
}

\draw[important] (0,0) -- (2,0);
\node[box] (a) {Input};
\draw[arrow] (a) -- ++(2,0);
\draw[myline={blue}{1.5pt}] (0,1) -- (2,1);

Styles may include other styles (box, important), so a diagram's look can be changed in one place. A picture-wide style goes in the options of the environment: \begin{tikzpicture}[box/.style={...}]. Put shared styles in your preamble or a style file (custom commands) so all your figures look alike.

Calculations with the calc library

LATEX
\usetikzlibrary{calc}

\coordinate (A) at (0,0);
\coordinate (B) at (4,2);
\coordinate (M) at ($(A)!0.5!(B)$);          % midpoint
\coordinate (P) at ($(A)+(1,2)$);            % vector addition
\draw ($(A)+(0,-1)$) -- ($(B)+(0,-1)$);      % parallel shifted line
\draw (A) -- ($(A)!1cm!90:(B)$);             % 1 cm perpendicular to A--B
\draw (A) -- (intersection of A--B and C--D);   % intersections library

The $...$ syntax is a small coordinate calculator. The intersections library names paths and finds crossings:

LATEX
\usetikzlibrary{intersections}
\path[name path=line1] (0,0) -- (4,3);
\path[name path=line2] (0,3) -- (4,0);
\fill[name intersections={of=line1 and line2}] (intersection-1) circle (2pt);

Useful libraries

Library Purpose
arrows.meta Modern arrow tips
positioning right=of placement
shapes.geometric, shapes.misc Diamond, cylinder, cross out
decorations.pathmorphing Wavy and zigzag lines (decorate, decoration={zigzag})
decorations.markings Arrows in the middle of a path
patterns Hatching and dots
shadows, fadings, shadings Soft effects; gradients with left color=..., right color=...
fit, backgrounds Draw a box around a group of nodes; place it behind them
calc, intersections Coordinate maths
3d, perspective Simple 3D figures
mindmap, trees, er, automata Specialised diagrams

Load several at once: \usetikzlibrary{arrows.meta, positioning, calc, fit, backgrounds}.

Layers

By default shapes are drawn in source order; later ones cover earlier ones. The backgrounds library provides a layer:

LATEX
\begin{pgfonlayer}{background}
  \node[fit=(a)(b)(c), draw, fill=yellow!20, inner sep=6pt] {};
\end{pgfonlayer}

with \pgfdeclarelayer{background} and \pgfsetlayers{background,main} declared beforehand.

Speeding up and debugging

  • \usetikzlibrary{external} and \tikzexternalize: compile each picture once into a PDF and reuse it. It needs -shell-escape and is a big time saver in documents with many figures.
  • Standalone class: make each figure a tiny document, \documentclass[tikz,border=5pt]{standalone}, so you can iterate quickly, then include the PDF or the code with \input.
  • Common errors: a missing semicolon ("Package tikz Error: Giving up on this path"), an unknown style, or a loop variable missing its backslash. Read the first error message and the line number.
  • Use show background grid: add \draw[help lines] (0,0) grid (5,5); during design.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does \foreach \x in {0,0.5,...,2} iterate over?

    The dots tell TikZ to continue with the same step until the final value.
  2. 2. How do you define a reusable set of options named box?

    Styles are created with \tikzset and the /.style handler.
  3. 3. What does $(A)!0.5!(B)$ compute with the calc library?

    The !t! syntax interpolates a point at fraction t along the line from A to B.
  4. 4. What is the main benefit of the external library?

    Externalisation compiles each tikzpicture once and reuses the result in later runs.

Summary

  • \foreach repeats drawings over lists and ranges, and works with coordinates.
  • \tikzset styles bundle options and can take parameters.
  • The calc and intersections libraries compute points and crossings.
  • Libraries add arrows, shapes, decorations, fitting and backgrounds.
  • external and standalone speed up compiles.

Next: Charts and Plots with PGFPlots