6

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

\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{arrows, chains, fit, quotes}
\begin{document}
\begin{tikzpicture}
    \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$};
\end{tikzpicture}
\end{document}

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.

0

2 Answers 2

9

exploiting chains library and uses labels for text below nodes:

\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{arrows, chains}

\begin{document}
    \begin{tikzpicture}[
  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$};
\end{tikzpicture}
\end{document}

enter image description here

4
  • I think both are very valid solutions
    – gtatr
    Commented Dec 11, 2016 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
    Commented Dec 11, 2016 at 19:24
  • Instead of \#0 can we use a math string like $a_{n}$ ?
    – alper
    Commented Dec 24, 2022 at 16:49
  • 1
    @alper. Of course. Just replace {\#0, \#0, \#1, \#2, \#1 with desired string. For example with {a_0, a_0, a_1, a_2, a_1} ot any other sequences.
    – Zarko
    Commented Dec 24, 2022 at 16:58
6

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

enter image description here

    \documentclass[border={10pt}]{standalone}

\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture}
    [%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        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};

\end{tikzpicture}

\end{document}
2
  • \foreach [count=\index from 0] ... saves you the \pgfmathtruncatemacro. Commented Dec 10, 2016 at 22:02
  • @TorbjørnT., you beat me with 1 sec. I was modifying the answer. Thanks any way. Cheers.
    – CroCo
    Commented Dec 10, 2016 at 22:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .