I want to write some text under the rectangles drawn using tikz, to draw an array and its indices. Here is a mwe:

\usetikzlibrary{arrows, chains, fit, quotes}
    \draw (0,0) rectangle (1,1) node[pos=.5] {$\#0$}; %node[anchor=north, pos=.5]{0};
    \draw (1,0) rectangle (2,1) node[pos=.5] {$\#0$};
    \draw (2,0) rectangle (3,1) node[pos=.5] {$\#1$};
    \draw (3,0) rectangle (4,1) node[pos=.5] {$\#2$};
    \draw (4,0) rectangle (5,1) node[pos=.5] {$\#1$};
    \foreach \x in {0,1,2,3,4}
        \draw (\x cm,0pt) -- (\x cm,0pt) node[anchor=north, pos=.5] {$\x$};

Here is the result result What I'd like to achieve is each number (those without #) centered under each box.

I also tried to use another node as in the comment, but can't manage to position it under the box and centered.


exploiting chains library and uses labels for text below nodes:

\usetikzlibrary{arrows, chains}

  node distance = 0mm,
    start chain = going right,
     box/.style = {draw, semithick, minimum size=1cm, 
                   outer sep = 0mm, on chain}
\foreach \i [count=\j from 0] in {\#0, \#0, \#1, \#2, \#1}
    \node[box,label=below:\j] {$\i$};

enter image description here

  • I think both are very valid solutions – gtatr Dec 11 '16 at 18:35
  • I set this as correct answer as I can also edit the minimum size to a lower value without making the box appear separated. – gtatr Dec 11 '16 at 19:24

You can create node under each box. This is a possible solution for your problem.

enter image description here




        node distance=1mm,
        box/.style={rectangle,draw=black, ultra thick, minimum size=1cm},

\foreach \y [count=\x from 0] in {\#0,\#0,\#1,\#2,\#1}
     \node[box] (\x) at (\x,0) {\y} node[below=of \x] {\x};


  • \foreach [count=\index from 0] ... saves you the \pgfmathtruncatemacro. – Torbjørn T. Dec 10 '16 at 22:02
  • @TorbjørnT., you beat me with 1 sec. I was modifying the answer. Thanks any way. Cheers. – CroCo Dec 10 '16 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.