由于对 Latex 还不熟悉,我写下了以下 Tex 代码:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,positioning,arrows.meta,arrows}
\tikzset{
mymat/.style={
matrix of math nodes,
text height=2.5ex,
text depth=0.75ex,
text width=3.25ex,
align=center,
column sep=-\pgflinewidth
},
mymats/.style={
mymat,
nodes={draw,fill=#1}
}
}
\begin{document}
\begin{tikzpicture}[>=latex]
\node(array_a) {Array A};
\matrix[mymat,right=of array_a,row 2/.style={nodes=draw}]
at (0,0)
(mat1)
{
0 & 1 & 2 & 3 & 4 \\
2 & 1 & 3 & 2 & 1 \\
};
\end{tikzpicture}
\end{document}
结果是:
我们可以看到数组名称与 y 轴上的数组图示不对齐。
有人可以建议我该如何修复它吗?
谢谢
答案1
正如 daleif 所建议的,将标签放在矩阵后面更容易。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,positioning,arrows.meta,arrows}
\tikzset{
mymat/.style={
matrix of math nodes,
text height=2.5ex,
text depth=0.75ex,
text width=3.25ex,
align=center,
column sep=-\pgflinewidth
},
mymats/.style={
mymat,
nodes={draw,fill=#1}
}
}
\begin{document}
\begin{tikzpicture}[>=latex]
\matrix[mymat, row 2/.style={nodes=draw, anchor=center}]
at (0,0)
(mat1)
{
0 & 1 & 2 & 3 & 4 \\
2 & 1 & 3 & 2 & 1 \\
};
\node[left = 12mm of mat1-2-1.base, anchor=base] (array_a) {Array A};
\end{tikzpicture}
\end{document}
另一种解决方案是使用matrix anchor
选项来选择内部节点作为参考:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,positioning,arrows.meta,arrows}
\tikzset{
mymat/.style={
matrix of math nodes,
text height=2.5ex,
text depth=0.75ex,
text width=3.25ex,
align=center,
column sep=-\pgflinewidth
},
mymats/.style={
mymat,
nodes={draw,fill=#1}
}
}
\begin{document}
\begin{tikzpicture}[>=latex]
\node (array_a) {Array A};
\matrix[mymat, row 2/.style={nodes=draw},
right=of array_a, matrix anchor=mat1-2-1.west]
at (0,0)
(mat1)
{
0 & 1 & 2 & 3 & 4 \\
2 & 1 & 3 & 2 & 1 \\
};
\end{tikzpicture}
\end{document}
答案2
这个怎么样?
\documentclass[tikz,border=5mm]{standalone}
\begin{document}
\begin{tikzpicture}[scale=.8]
\draw (0,0) grid (5,1);
\foreach \i/\j in {0/2,1/1,2/3,3/2,4/1}
\path (\i+.5,1.5) node{\i} (\i+.5,.5) node{\j};
\path (-.5,.5) node[left]{Array A};
\end{tikzpicture}
\end{document}
更新:水平对齐
\documentclass[tikz,border=5mm]{standalone}
\begin{document}
\begin{tikzpicture}[scale=.8]
\draw (0,0) grid (5,1);
\foreach \i/\j in {0/2,1/1,2/3,3/2,4/1}
\path (\i+.5,1.5) node {\i} (\i+.5,.5) node (\i) {\j};
\path (0.base) node[left=1.5cm,anchor=base]{Array A};
% for checking baseline alignment only
\draw[red] (0.base)--++(0:5) (0.base)--++(180:3);
\end{tikzpicture}
\end{document}
答案3
与。{NiceTabular}
nicematrix
\documentclass{article}
\usepackage{nicematrix}
\begin{document}
Array A\quad
\begin{NiceTabular}{ccccc}[hvlines,first-row,baseline=0]
0 & 1 & 2 & 3 & 4 \\
2 & 1 & 3 & 2 & 1 \\
\end{NiceTabular}
\vspace{2cm}
Array A\quad
\begin{NiceTabular}{ccccc}[hvlines,first-row,baseline=1]
0 & 1 & 2 & 3 & 4 \\
2 & 1 & 3 & 2 & 1 \\
\end{NiceTabular}
\end{document}
您需要多次编译(因为nicematrix
在后台使用 PGF/Tikz 节点)。