# Aligning matrix of nodes with grid

I am trying to render a grid of stones using the code below, however when I remove the stone in m-3-1, the stones above and to the right of it (particularly m-1-5) will be off-center:

\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{matrix,shapes.geometric}
\newcommand\stone[0]{|[circle, shading=ball, ball color=black!80!white, minimum size=.8cm]|} % https://tex.stackexchange.com/a/184068/45824
\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
anchor=south west,
column sep={1cm,between origins},
row sep={1cm,between origins},
nodes in empty cells,
]
{
&        &        &        & \stone \\
&        &        &        &        \\
\stone &        &        &        &        \\
};
\draw[step=1cm,color=gray] (0,0) grid (5,3);
\draw[thick,red,->] (m-1-1) -> (m-1-5);
\draw[thick,red,->] (m-1-5) -> (m-3-5);
\end{tikzpicture}
\end{document}


How do I ensure all the stones are aligned correctly?

• First: don't use \tikzstyle. Use \tikzset instead. – user156344 Apr 14 '19 at 16:48
• @JouleV thanks, I moved it into the \newcommand definition. – Jan Tojnar Apr 14 '19 at 16:55

### Cause of issue

First, your "working" code doesn't even output the intended diagram: the circles are not aligned yet

Adding option draw to every nodes in the "not working" code gives us

which can explain the problem: your nodes are aligned correctly, but the matrix itself is not at the right place.

### Solution

• Use \tikzset
• Add option inner sep
• Use minimum size option for nodes
• Use anchor center for the arrows (see more below)

\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{matrix,shapes.geometric}
\newcommand\stone{|[stone]|} % https://tex.stackexchange.com/a/184068/45824
\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
anchor=south west,
column sep={1cm,between origins},
row sep={1cm,between origins},
nodes in empty cells,
nodes={minimum size=1cm},
inner sep=0pt
]
{
&        &        &        & \stone \\
&        &        &        &        \\
&        &        &        &        \\
};
\draw[step=1cm,color=gray] (0,0) grid (5,3);
\draw[thick,red,->] (m-1-1.center) -> (m-1-5);
\draw[thick,red,->] (m-1-5) -> (m-3-5.center);
\end{tikzpicture}
\end{document}