Search code examples
latextikz

Need a suggestion for counting a number vertically in a node created by TikZ


The goal is to create a node with a label in it. A label must count vertically from column 1, then proceed into another column. After doing some research with the "foreach" statement, I achieved this result by using this code.

\documentclass{minimal}
\usepackage{tikz}
\tikzstyle{d}=[draw,circle,minimum size=10mm]
\begin{document}
\begin{tikzpicture}
\foreach \x in {1,2,3}
\foreach \y in {-1,...,-5}{
    \node[d] at (1.5*\x,1.5*\y) {};
    }
\foreach \x in {1}
\foreach \y in {-1,...,-5}{
    \pgfmathtruncatemacro{\label}{-\y+\x-1}
    \node at (1.5*\x,1.5*\y) {\label};
    }
\foreach \x in {2}
\foreach \y in {-1,...,-5}{
    \pgfmathtruncatemacro{\label}{-\y+\x+3}
    \node at (1.5*\x,1.5*\y) {\label};
    }
\foreach \x in {3}
\foreach \y in {-1,...,-5}{
    \pgfmathtruncatemacro{\label}{-\y+\x+7}
    \node at (1.5*\x,1.5*\y) {\label};
    }
\end{tikzpicture}
\end{document}

enter image description here

Is there a simpler or more efficient way to achieve the same result? Any advice is welcome, and I am grateful for it.


Solution

  • Not sure about "simpler" but the code can definitely be more "parametric", hence easier to alter. You can use evaluate inside \foreach loops as well as macros, such as \pgfmathsetmacro{<name>}{<value>}. Also, the style d can be parameterised inlcuding the default value

    \documentclass{article}
    \usepackage{tikz}
    \tikzset{
      d/.style = {draw,circle,minimum size=#1},   % d is parametrised with
      d/.default = 10mm,                          % the default value of 10 mm
    }
    \begin{document}
    \begin{tikzpicture}
      \pgfmathsetmacro{\scale}{1.25}     % parameters for the grid
      \pgfmathsetmacro{\maxcols}{3}
      \pgfmathsetmacro{\maxrows}{5}
      \foreach \j in {1,...,\maxcols} {
        \foreach \i [
          evaluate=\n using {int(\i+\maxrows*(\j-1))},
          evaluate=\y using {\scale*(\maxcols-\i-1)},
          evaluate=\x using {\scale*(\j-1)},
        ] in {1,...,\maxrows} {
        \node[d=12mm] at (\x, \y) {\n};}}
    \end{tikzpicture}
    \end{document}