代码:
\begin{tikzpicture}
\matrix[matrix of math nodes, anchor=south west,
nodes={
draw=red,
align=center,
inner sep=0pt,
text width=1cm - \pgflinewidth,
minimum size = 1cm - \pgflinewidth
}
]{
A & B & D & B & A & C & E & G & E & H & E & C & F & I & F & C & A \\
0 & 1 & 2 & 1 & 0 & 1 & 2 & 3 & 2 & 3 & 2 & 1 & 2 & 3 & 2 & 1 & 0 \\
};
\foreach \x in {0,...,16}
\node[align=center] at (\x+1,0) {\x};
\end{tikzpicture}
输出:
我该如何编写 LaTeX 程序,让矩阵的上下连续的数字与矩阵的列相对应?像这样:
答案1
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[matrix of math nodes, anchor=south west,
nodes={
draw=red,
align=center,
inner sep=0pt,
text width=1cm - \pgflinewidth,
minimum size = 1cm - \pgflinewidth
}
]{
A & B & D & B & A & C & E & G & E & H & E & C & F & I & F & C & A \\
0 & 1 & 2 & 1 & 0 & 1 & 2 & 3 & 2 & 3 & 2 & 1 & 2 & 3 & 2 & 1 & 0 \\
};
\foreach \x in {0,...,16}
\node[align=center] at (\x+0.62,-0.04) {\x};
\end{tikzpicture}
\end{document}
答案2
另一种解决方案是自动将列标签写入最后一行元素的下方。
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[matrix of math nodes, anchor=south west,
column sep=-\pgflinewidth,
row sep=-\pgflinewidth,
nodes={
draw=red,
align=center,
outer sep=0pt,
inner sep=0pt,
text width=1cm,
minimum size = 1cm
},
row 2/.style={execute at begin cell={%
|[label={[minimum size=6mm]below:\the\numexpr\pgfmatrixcurrentcolumn-1}]|},}
]{
A & B & D & B & A & C & E & G & E & H & E & C & F & I & F & C & A \\
0 & 1 & 2 & 1 & 0 & 1 & 2 & 3 & 2 & 3 & 2 & 1 & 2 & 3 & 2 & 1 & 0 \\
};
\end{tikzpicture}
\end{document}
答案3
非常简单的一个
\documentclass[tikz]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[matrix of math nodes, anchor=south west,
nodes={
draw=red,
align=center,
inner sep=0pt,
text width=1cm - \pgflinewidth,
minimum size = 1cm - \pgflinewidth
}
]{
A & B & D & B & A & C & E & G & E & H & E & C & F & I & F & C & A \\
0 & 1 & 2 & 1 & 0 & 1 & 2 & 3 & 2 & 3 & 2 & 1 & 2 & 3 & 2 & 1 & 0 \\
};
\foreach \x in {0,...,16}
\node[%
gray,
anchor=north east,
align=center,
text width=\pgflinewidth,
minimum size = 1cm - \pgflinewidth
]%
at (\x+1,0) {\x};
\end{tikzpicture}
\end{document}
答案4
没有matrix
,更短,更简单?
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{chains, positioning}
\begin{document}
\begin{tikzpicture}[
node distance = 0pt,
start chain = going right,
box/.style = {draw=red, minimum size=10mm, outer sep=0pt}
]
\foreach \i/\j [count =\k from 0] in {
A/0, B/1, D/2, B/1, A/0, C/1, E/2, G/3,
E/2, H/3, E/2, C/1, F/2, I/3, F/2, C/1,
A/0}
{
\node (n\k) [box,on chain] {\i};
\node [box, below=of n\k, label={[text=gray]below:\k}] {\j};
}
\end{tikzpicture}
\end{document}