## Sunday, December 11, 2022

### Experimenting with foreach loops in TikZ to draw biochemical pathways

Here is an example of a foreach loop in TikZ that can be used to draw an arbitrary long linear chain of reactions.

By setting the value of N in the following TikZ code, you can get any length linear chain. Obviously, you're limited by the width of the page. It uses the xifthen package to provide a conditional that is used to print out the last species, which is X1. There could be a better way of doing this, but this works. For example, use newcommand instead of def

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{calc}
\usepackage{xifthen}

\begin{document}

\begin{tikzpicture}[>=latex', node distance=2cm]
\node (X0) {$X_o$};
\pgfmathsetmacro{\N}{4}
\foreach \x in {0,...,\N}
{
\pgfmathtruncatemacro{\nextval}{\x+1}
\ifthenelse{\x = \N}
{\def\speciesName{$X_1$}}
{\def\speciesName{\large $x_\nextval$}}

\node [right of = X\x] (X\nextval) {\speciesName};
\draw [->,ultra thick,blue] (X\x) -- node[above, black] {$v_{\nextval}$} (X\nextval);
}
\end{tikzpicture}

\end{document}


Here are some examples for N = 0, N = 2 and N = 4