[Tex/LaTex] Drawing Grid Lines using \foreach

foreachtikz-pgf

I am trying to draw gridlines inside a square. Here is my code:

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}

\begin{figure}[ht]

\centering

\begin{tikzpicture}[scale=1.25,line width=1pt]
\begin{axis}[
color= white,
xmin=-28.9, 
xmax=28.9, 
ymin=-28.9, 
ymax=28.9, 
axis equal image, 
axis lines=middle,
]

\foreach \x in {-24,..., 24}
    {\draw[thin, gray] (\x,-24) -- (\x,24);}

\draw[black, thin] (-24,-24) -- (-24,24) -- (24,24) -- (24, -24) -- 
(-24,-24);

\node[black, below] at (24,-24) {$(1,0)$};

\node[black, below] at (-24,-24) {$(0,0)$};

\node[black, above] at (-24,24) {$(0,1)$};

\node[black, above] at (24,24) {$(1,1)$};

\end{axis}
\end{tikzpicture}

\end{figure}

\end{document}

This code, however, will not compile. My goal is to make a square with a 24 x 24 grid.

Best Answer

Works fine if you use \pgfplotsinvokeforeach instead of \foreach:

enter image description here

Notes:

  • I would suggest you try the grid options built into pgfplots and tikz.
  • All the code you showing does not require pgfplots so you can eliminate the axis environment. So, unless there is other functionality that is not shown in the MWE, you should consider the non-axis environment version which uses \foreach.

References:

Code: pgfplots

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}
%
%\begin{figure}[ht]
%
%\centering
%
\begin{tikzpicture}%[scale=1.25,line width=1pt]
\begin{axis}[
    color= white,
    xmin=-28.9, 
    xmax=28.9, 
    ymin=-28.9, 
    ymax=28.9, 
    axis equal image, 
    axis lines=middle,
]

\pgfplotsinvokeforeach {-24,...,24} {%
    \draw[thin, gray] (#1,-24) -- (#1,24);
}

\draw[black, thin] (-24,-24) -- (-24,24) -- (24,24) -- (24, -24) -- 
(-24,-24);

\node[black, below] at (24,-24) {$(1,0)$};

\node[black, below] at (-24,-24) {$(0,0)$};

\node[black, above] at (-24,24) {$(0,1)$};

\node[black, above] at (24,24) {$(1,1)$};

\end{axis}
\end{tikzpicture}%
%
%\end{figure}
%
\end{document}

Code: no pgfplots

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}
\begin{tikzpicture}[scale=0.10]

\foreach \x in  {-24,...,24} {%
    \draw[thin, gray] (\x,-24) -- (\x,24);
}

\draw[black, thin] (-24,-24) -- (-24,24) -- (24,24) -- (24, -24) -- 
(-24,-24);

\node[black, below] at (24,-24) {$(1,0)$};

\node[black, below] at (-24,-24) {$(0,0)$};

\node[black, above] at (-24,24) {$(0,1)$};

\node[black, above] at (24,24) {$(1,1)$};

\end{tikzpicture}%
\end{document}