[Tex/LaTex] TikZ (finite) grid with character in each cell

tikz-pgf

The code

\begin{tikzpicture}
\draw[step=0.5cm,color=gray] (-1,-1) grid (1,1);
\end{tikzpicture}

gives me a nice finite 4×4 grid. Now I want to center one character in each cell, how to do this?

By the way, how can I specify the absolute position of my picture and how to stretch it in one direction (i.e. that it becomes a proper rectangle (not a square)).

Best Answer

You can use \nodes to place text everywhere you want. The are by default centered at the given coordinate which can be changed using the anchor and other options.

\documentclass{article}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw[step=0.5cm,color=gray] (-1,-1) grid (1,1);
\node at (-0.75,+0.75) {A};
\node at (-0.25,+0.75) {B};
\node at (+0.25,+0.75) {C};
\node at (+0.75,+0.75) {D};
\node at (-0.75,+0.25) {E};
\node at (-0.25,+0.25) {F};
\node at (+0.25,+0.25) {G};
\node at (+0.75,+0.25) {H};
% ...
\node at (+0.75,-0.75) {Q};
\end{tikzpicture}
\end{document}

Result


Or using a loop:

\documentclass{standalone}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw[step=0.5cm,color=gray] (-1,-1) grid (1,1);

\newcounter{mycount}
\setcounter{mycount}{`A}
\foreach \y in {+0.75,+0.25,-0.25,-0.75}
  \foreach \x in {-0.75,-0.25,0.25,0.75}
    \node at (\x,\y) {\char\value{mycount}\addtocounter{mycount}{1}};
\end{tikzpicture}%

% Or
\begin{tikzpicture}
\draw[step=0.5cm,color=gray] (-1,-1) grid (1,1);
\foreach \x/\y/\m in {+0.75/+0.75/A,-0.75/-0.75/X} % etc
    \node at (\x,\y) {\m};
\end{tikzpicture}%

\end{document}

Loop result Loop result 2


You can scale the image in the X or Y direction using xscale=<number> and yscale=<number>, respectively. Both are scaled with scale=<number>.

If you mean with "absolute position" a fixed position on a page you can do this by drawing it relative to the special current page node (needs the remember picture,overlay option on the picture). If you give more specific information about this I can make an example.