我想在使用 tikz 绘制的矩形下写一些文本,以绘制一个数组及其索引。这是一个 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}
结果如下 我想要实现的是每个数字(没有#的数字)都位于每个框的中央。
我也尝试使用评论中的另一个节点,但无法将其放置在框下方并居中。
答案1
利用chains
库并使用节点下方的文本标签:
\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}
答案2
您可以在每个框下创建节点。这是解决您问题的一种可能方法。
\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}