Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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

share|improve this question
1  
What is the specific reason to use pgfplots? It seems to me that a tikz solution would do the job just fine. But I don't know your final/complete use case. –  Paul Gessler Jun 7 at 1:20
    
Sorry for the confusion. I meant I wanted to use a tikzpicture in my LaTeX document. –  A2009 Jun 7 at 1:37

2 Answers 2

up vote 7 down vote accepted

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

share|improve this answer

Here is a solution using grid...

\documentclass[tikz,margin=1mm]{standalone}

\newcommand\mygrid[1]{
  \begin{tikzpicture}
    \draw[black,line width=1pt] (0,0) grid[step=1] (#1,#1);
    \draw[red,line width=1pt]   (0,0) grid[step=2] (#1,#1);
    \draw[black,line width=4pt] (0,0) grid[step=4] (#1,#1);
    \draw[black,line width=4pt] (0,0) rectangle (#1,#1);
  \end{tikzpicture}
}

\begin{document}
  \mygrid{4}
  \mygrid{8}
  \mygrid{16}
  \mygrid{32}
\end{document}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.