Draw a commutative diagram in LaTeX (tikz-cd)
The tikzcd environment from the tikz-cd package arranges the objects in a grid like a matrix, with & between columns and \\ between rows. \arrow[r, "f"] draws an arrow to the cell on the right and labels it with f.
Preamble
The snippets on this page need these lines before \begin{document}:
\usepackage{tikz-cd}Draw a commutative square
Every cell is set in math mode. An \arrow starts in the cell where it is written; the letters r, l, u and d give the direction of its target (right, left, up, down). The label stands in quotes, and an apostrophe after it, as in "g"', moves it to the other side of the arrow.
\begin{tikzcd}
A \arrow[r, "f"] \arrow[d, "g"'] & B \arrow[d, "h"] \\
C \arrow[r, "k"'] & D
\end{tikzcd}Draw diagonal, long and bent arrows
Several letters combine to a path through the grid: rd ends one cell to the right and one down, rr two cells to the right. bend left curves an arrow, and shift left moves it sideways, so two arrows between the same cells run in parallel.
\begin{tikzcd}
A \arrow[r, "f"] \arrow[rd, "g \circ f"'] \arrow[rr, bend left, "h"] & B \arrow[d, "g"] & D \\
& C &
\end{tikzcd}
\qquad
\begin{tikzcd}
X \arrow[r, shift left, "p"] \arrow[r, shift right, "q"'] & Y
\end{tikzcd}Choose the arrow type
Options change the shaft and the tip: hook for an inclusion, two heads for a surjection, dashed for a dashed shaft, Rightarrow for a double arrow, maps to for an arrow with a bar at its start and equal for a double line without a tip.
\begin{tikzcd}
A \arrow[r, hook] & B \arrow[r, two heads] & C \arrow[r, dashed, "\exists!"] & D \\
E \arrow[r, Rightarrow] & F \arrow[r, maps to] & G \arrow[r, equal] & H
\end{tikzcd}Set the spacing and number the diagram
column sep and row sep take a length or one of the names tiny, small, scriptsize, normal, large and huge. Inside an equation environment the diagram gets an equation number.
\begin{equation}
\begin{tikzcd}[column sep=large]
0 \arrow[r] & A \arrow[r, "f"] & B \arrow[r, "g"] & C \arrow[r] & 0
\end{tikzcd}
\end{equation}Pitfalls
- With
\usepackage[ngerman]{babel}, the quotation mark is a shorthand character and the labels in quotes cause errors. Add\usetikzlibrary{babel}after loadingtikz-cd. - Inside the argument of another command, for example
\footnoteor\fbox, the&stops with the error "Single ampersand used with wrong catcode". Write\begin{tikzcd}[ampersand replacement=\&]and use\&between the cells.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- Package
tikz-cd - Package
tikz - Package
babel - How-to Draw with TikZ in LaTeX
- How-to Matrices in LaTeX