I am new to the use of TikZ. I have been evaluating the TikZ-KTikZ combination, over the last 2 days, as an alternative to Xfig, which I have used for 17 years. I have managed to create a grid structure using the following code:
\begin{tikzpicture}
\newcommand{\GL}{5};
\draw [step=0.1, help lines,red!20] (-\GL,-\GL) grid (\GL,\GL);
\draw [step=1.0, help lines,red!40] (-\GL,-\GL) grid (\GL,\GL);
\draw [step=\GL.0, help lines,red!100] (-\GL,-\GL) grid (\GL,\GL);
\foreach \x in {-\GL,...,\GL} { \draw node at (\x,-\GL) [label=below:{\tiny $\x.0$}]{}; };
\foreach \x in {-\GL,...,\GL} { \draw node at (\x,\GL) [label=above:{\tiny $\x.0$}] {}; };
\foreach \y in {-\GL,...,\GL} { \draw node at (-\GL,\y) [label=left:{\tiny $\y.0$}] {}; };
\foreach \y in {-\GL,...,\GL} { \draw node at (\GL,\y) [label=right:{\tiny $\y.0$}] {}; };
\end{tikzpicture}
I like using the grid structure because it enables me to place my picture elements in the {tikzpicture} environment quickly. However, I have to comment it out after drawing my picture. I would like to package the above code into a single flexible command which I can insert into the {tikzpicture} and comment out quickly when I am done.
Could someone with a lot of experience in TikZ advise me on how I could package the above code into a single command which could accept optional parameters such as Xmin, Xmax, Ymin, Ymax and grid color, with default values.
Any help would be greatly appreciated.
Best Answer
Here is a solution via
pgfkeys
.First, I create the new family
mygrid
, I define some keys with their initial values in this family and I define the new command\mygridset
to use this family:Then I define the new command
\mygrid
with an empty optional parameter. The first lines of this command (the call to\mygridset
) changes the values of the keys via#1
then store the value of each key in a macro. The last lines draw the grid with these values.Here is a complete example (3 pages) to illustrate the usage:
And the complete code: