[Tex/LaTex] add grid on matrix

tikz-matrixtikz-pgf

MWE:

\documentclass[tikz,margin=2pt]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw,circle,minimum size=1em, outer sep=0pt,inner sep=0,line width=0.5pt},
             nodes in empty cells,column sep=1em, row sep=1em,
              ]
{
   1  & 2 & 3  \\
    4 & 5 & 6  \\
    7 & 8 & 9  \\
};
\end{tikzpicture}
\end{document}

I want to add grid for each cell just like a table!

enter image description here

Best Answer

Since you already used up the node style for the circles, you may just draw the lines afterwards. This also allows you to skip the outer lines.

\documentclass[tikz,margin=2pt]{standalone}
\usetikzlibrary{matrix,calc}
\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw,circle,minimum size=1em, outer sep=0pt,inner sep=0,line width=0.5pt},
             nodes in empty cells,column sep=1em, row sep=1em,
              ]
{
   1  & 2 & 3  \\
    4 & 5 & 6  \\
    7 & 8 & 9  \\
};
\foreach \X [count=\n] in {2,3} {
\draw ($(m-1-\n.north)!0.5!(m-1-\X.north)$) -- ($(m-3-\n.south)!0.5!(m-3-\X.south)$);
\draw ($(m-\n-1.west)!0.5!(m-\X-1.west)$) -- ($(m-\n-3.east)!0.5!(m-\X-3.east)$);
}
\end{tikzpicture}
\end{document}

enter image description here

UPDATE: And if you want a full grid, you could also do

\documentclass[tikz,margin=2pt]{standalone}
\usetikzlibrary{matrix,calc}
\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw,circle,minimum size=1em, outer sep=0pt,inner sep=0,line
             width=0.5pt,append after command={\pgfextra{\draw 
             ($(\tikzlastnode.north west)+(-0.5em,+0.5em)$)
             rectangle ($(\tikzlastnode.south east)+(0.5em,-0.5em)$);}}},
             nodes in empty cells,column sep=-0.5pt, row sep=-0.5pt
              ]
{
   1  & 2 & 3  \\
    4 & 5 & 6  \\
    7 & 8 & 9  \\
};
\end{tikzpicture}
\end{document}

matrix with grid & border