A tikz macro for drawing axes and grid for LaTeX

posted in: LaTeX | 0

I’m writing something that requires me to draw many plots in the Cartesian plane R2 and so I wrote this macro to simplify the process. The arguments are

  1. The optional tikzpicture scaling factor
  2. The x-coordinate of the lower left corner
  3. The y-coordinate of the lower left corner
  4. The x-coordinate of the upper right corner
  5. The y-coordinate of the upper right corner
  6. The label for the horizontal axis
  7. The label for the vertical axis

It behaves nicely if any of the coordinates are 0 but does no checking for the values or placement of the corners.

I have a separate macro \tikzGridColor that defines the grid color. At the moment it is set to a shade of blue so the graph looks like it is done on graph paper.

Scroll right to see all the code.

[sourcecode language=”tex”]

\usetikzlibrary{angles,quotes,arrows,positioning}
\usetikzlibrary{arrows.meta,calc,patterns}
\usetikzlibrary{decorations.pathreplacing,backgrounds}

\def\tikzGridColor{blue!75!white}

\newcommand{\graphGridTwoD}[7][0.5]{
\draw[step=#1,\tikzGridColor,very thin] (#2-0.9,#3-0.9) grid (#4+0.9,#5+0.9);
\draw[thick,<->] (#2-0.75,0) — (#4+0.75,0) node[below] {\small #6};
\draw[thick,<->] (0,#3-0.75) — (0,#5+0.75) node[left] {\small #7};
\ifthenelse{#2<0} {\foreach \x in {#2,…,-1}
\draw[thick] (\x,.1) — (\x,-.1) node[below] {\tiny$\x$};
}{}
\ifthenelse{#4>0} {\foreach \x in {1,…,#4}
\draw[thick] (\x,.1) — (\x,-.1) node[below] {\tiny$\x$};
}{}
\ifthenelse{#3<0} {\foreach \y in {#3,…,-1}
\draw[thick] (.1,\y) — (-.1,\y) node[left] {\tiny$\y$};
}{}
\ifthenelse{#5>0} {\foreach \y in {1,…,#5}
\draw[thick] (.1,\y) — (-.1,\y) node[left] {\tiny$\y$};
}{}
\node[below left] at (0,0) {\tiny$0$};
}
[/sourcecode]