我制作了一个带坐标的棋盘。但我希望它位于开头 (0,0) 而不是 (3,0),代码如下:
\begin{tikzpicture}[scale=1.25]
\foreach \y in {0,1,...,3}
\foreach \x in {0,1,...,3}
{
%\draw[draw = gray] (\x,\y) +(-.5,-.5) rectangle ++(.5,.5);
\draw[draw = gray] (\x,\y) +(-.5,-.5) rectangle ++(.5,.5);
\draw (\x,\y) node{\small (\y,\x)};
}
\foreach \x in {0,1,...,3}{
\node[draw=red!70] at (\x,-1) {\x};
\node[draw=blue!80] at (-1,\x) {\x};
}
%\draw [thick,red!50!black, -Stealth] (-3,0) -- node[above=1mm] {row} (-1.5,0);
%\draw [thick,blue!50!black, -Stealth] (0,-3) -- node[below=10mm] {column} (0,-1.5);
\end{tikzpicture}
我得到的结果为:[3,0] [3,1] [3,2] [3,3] 但我想要的是:[0,0] [0,1] [0,2] [0,3] 并且行和列也应该位于网格下方。我该如何解决这个问题?
答案1
另一种方法是使用节点,而不是绘制矩形并放置节点。由于您使用该scale
选项,因此您需要获取缩放的 x/y 单位,以便能够在节点选项中使用它们。无论如何,您只需要两个\foreach
循环:
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[scale=1.25]
\path (1,1);
\pgfgetlastxy{\unitx}{\unity}
\foreach \x in {0,...,3}{
\node[draw=red!70] at (\x,1) {\x};
\foreach \y in {0,...,3}{
\node[draw=blue!80] at (-1,-\y) {\y};
\node[draw = gray, minimum width=\unitx, minimum height=\unity] at (\x,-\y) {\small (\x,\y)};
}
}
\end{tikzpicture}
\end{document}
答案2
Amatrix
也是一个有效的解决方案:
\documentclass[tikz, border=2mm]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[matrix of nodes,
nodes={anchor=center, draw, minimum size=1cm},
row sep=-\pgflinewidth,
column sep=-\pgflinewidth,
row 1/.style={nodes={draw=red, minimum size=3mm}},
column 1/.style={nodes={draw=blue, minimum size=3mm}}]{
&[3mm] 0 & 1 & 2 & 3\\[3mm]
0 & (0,0) & (0,1) & (0,2) & (0,3)\\
1 & (1,0) & (1,1) & (1,2) & (1,3)\\
2 & (2,0) & (2,1) & (2,2) & (2,3)\\
3 & (3,0) & (3,1) & (3,2) & (3,3)\\};
\end{tikzpicture}
\end{document}
答案3
我在这里找到了解决方案:
\begin{tikzpicture}[scale=1.25]
\foreach \x in {0,1,...,3}
\foreach \y in {0,1,...,3}
{
\draw[draw = gray] (\y,-\x) +(-.5,-.5) rectangle ++(.5,.5);
\draw (\y,-\x) node{\small (\x,\y)};
}
\foreach \x in {0,1,2,...,3}{
\node[draw=red!70] at (\x,1) {\x};
\node[draw=blue!80] at (-1,-\x) {\x};
}
%\draw [thick,red!50!black, -Stealth] (-3,0) -- node[above=1mm] {row} (-1.5,0);
%\draw [thick,blue!50!black, -Stealth] (0,-3) -- node[below=10mm] {column} (0,-1.5);
\end{tikzpicture}