[Tex/LaTex] Using tikzpicture or pgfplots to draw a uniform grid

pgfplotstikz-pgf

I want to use pgfplots or tikzpicture to draw a uniform grid as illustrated in below. The grid size in the figure is 8×8. I want to be able to define a parameter that gives me the ability to draw grids with different sizes, for example, 16×16 or 32×32. Could someone help me how I should do it?

enter image description here

Best Answer

With tikz

\documentclass[tikz,border=5pt]{standalone}
\newcommand{\Grid}[2]{%
  \def\maxX{#1}
  \def\maxY{#2}
  \begin{tikzpicture}
    \draw[line width=1pt] (0,0) rectangle (\maxX,\maxY);
    \foreach \x in {0,1,...,\maxX}{
    \draw (\x,0) -- (\x,\maxY);
    \draw[line width=1pt] (\maxX*0.5,0) -- (\maxX*0.5,\maxY);
    \draw[line width=1pt,red] (\maxX*0.25,0) -- (\maxX*0.25,\maxY);
    \draw[line width=1pt,red] (\maxX*0.75,0) -- (\maxX*0.75,\maxY);
    }
    %
    \foreach \y in {0,1,...,\maxY}{
    \draw (0,\y) -- (\maxX,\y);
    \draw[line width=1pt] (0,\maxY*0.5) -- (\maxX,\maxY*0.5);
    \draw[line width=1pt,red] (0,\maxY*0.25) -- (\maxX,\maxY*0.25);
    \draw[line width=1pt,red] (0,\maxY*0.75) -- (\maxX,\maxY*0.75);
    }
  \end{tikzpicture}
}
\begin{document}
  \Grid{8}{8}

  \Grid{4}{4}

  \Grid{16}{16}

  \Grid{32}{32}
\end{document}

enter image description here