在矩阵上添加网格

在矩阵上添加网格

梅威瑟:

\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}

我想像表格一样为每个单元格添加网格!

在此处输入图片描述

答案1

由于您已经用完了圆圈的节点样式,因此您可以稍后再绘制线条。这也允许您跳过外线。

\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}

在此处输入图片描述

更新:如果你想要一个完整的网格,你也可以这样做

\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}

带网格和边框的矩阵

相关内容