我正在尝试绘制一个二维数组,索引位于每行开头的框上方。有人能帮我把它们放在行的左边吗?
任何帮助是极大的赞赏!
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc, chains, positioning}
\begin{document}
\begin{tikzpicture}[
node distance = 6mm and 1mm,
start chain = going below,
box/.style = {draw, minimum size=8mm, on chain}
]
\node (n11) [box, label=0] {2};
\node [box, label=1] {1};
\node [box, label=2] {-9};
%
\begin{scope}[every node/.style={box}]
\node (n21) [right=of n11] {4};
\node {3};
\node {-8};
%
\node (n31) [right=of n21] {6};
\node {5};
\node {-7};
%
\node (n41) [right=of n31] {8};
\node {7};
\node {-6};
%
\end{scope}
\end{tikzpicture}
\end{document}
答案1
既然你正在编写一个数组,为什么不使用\matrix
?
如果您有一个包含多行的矩阵并且编写标签很无聊,那么您可以使用\foreach
。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\tikzset{
box/.style = {draw, minimum size=8mm},
}
\begin{document}
Matrix with labelled nodes:
\begin{center}
\begin{tikzpicture}[label distance=-4pt]
\matrix[
column sep = 1mm,
row sep = 6mm,
matrix of math nodes,
nodes={box},
] (M) {
|[label=left:0]|2 & 4 & 6 & 8 \\
|[label=left:1]|1 & 3 & 5 & 7 \\
|[label=left:2]|-9 & -8 & -7 & -6 \\
};
\end{tikzpicture}
\end{center}
Matrix with labels set by a \texttt{\textbackslash foreach}:
\begin{center}
\begin{tikzpicture}
\matrix[
column sep = 1mm,
row sep = 6mm,
matrix of math nodes,
nodes={box},
] (M) {
2 & 4 & 6 & 8 \\
1 & 3 & 5 & 7 \\
-9 & -8 & -7 & -6 \\
};
\foreach \i [evaluate=\i as \j using {int(\i-1)}] in {1,2,3}
\node at ([xshift=-2em]M-\i-1) {\j};
\end{tikzpicture}
\end{center}
\end{document}
答案2
您只需要声明标签位置。如果没有这个,则假定标签位于节点上方:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc, chains, positioning}
\begin{document}
\begin{tikzpicture}[
node distance = 6mm and 1mm,
start chain = going below,
box/.style = {draw, minimum size=8mm, on chain}
]
\node (n11) [box, label=left:0] {2};
\node [box, label=left:1] {1};
\node [box, label=left:2] {-9};
%
\begin{scope}[every node/.style={box}]
\node (n21) [right=of n11] {4};
\node {3};
\node {-8};
%
\node (n31) [right=of n21] {6};
\node {5};
\node {-7};
%
\node (n41) [right=of n31] {8};
\node {7};
\node {-6};
%
\end{scope}
\end{tikzpicture}
\end{document}
你将获得:
答案3
这样怎么样?
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc, chains, positioning}
\begin{document}
\begin{tikzpicture}[
node distance = 6mm and 1mm,
start chain = going below,
box/.style = {draw, minimum size=8mm, on chain}
]
\node (n11) [box] {2};
\node [left= of n11] {0};
\node (L1) [box] {1};
\node (L2) [box] {-9};
%
\begin{scope}[every node/.style={box}]
\node (n21) [right=of n11] {4};
\node {3};
\node {-8};
%
\node (n31) [right=of n21] {6};
\node {5};
\node {-7};
%
\node (n41) [right=of n31] {8};
\node {7};
\node {-6};
%
\end{scope}
\node [left = of L1] {1};
\node [left = of L2] {2};
\end{tikzpicture}
\end{document}