I'm drawing a TikZ figure and am going to need a couple of constant that I could easily change between compilations, e.g. a main radius, a proportion, a number of lines, etc. What is the preferred way of defining these?
It's not just one \draw
command, so I suppose I can't use let
.
Best Answer
Using
\newcommand
and\pgfmathsetmacro
:Since you are only planning on changing the parameter within the deepest
.tex
file containing thetikzpicture
, I would use\newcommand*{\Name}{}%
to set the values and the just use\Name
to access them.However, if the value of some of the parameters are mathematically computed from another, then I would recommend using
\pgfmathsetmacro{\NewName}{}
. For example:This will be very useful when the calculation is a bit more complex.
However, should you want to consider the ability to change them from the parent document, you could instead use
\providecommand{}{}
in thetikzpicture
document instead to set the parameter. This will then allow for the possibility that you could change the parameter in the parent document. One downside of this approach is that there is a risk that the value is defined somewhere else also no error will be triggered in thetikzpicture
.Using
\pgfmathsetnewmacro
:As pointed out in the comments
\pgfmathsetmacro
uses a\def
so no error is produced if you are overwriting an existing macro name. So, instead you could use\pgfmathsetnewmacro
as defined below -- this issues a\newcommand
to check that the macro does not already exist, before calling\pgfmathsetmacro
:If you are defining the values within the
tikzpicture
and are not worried about overriding any previously defined ones, then you can use\def
and\pgfmathsetmacro
.Update: Problems with using
\def
:The comments suggest that if you define these constants within the
tikzpicture
environment, any case of accidentally overwriting an existing macro via a\def
or\pgfmathsetmacro
will not result in any problems outside of thetikzpicture
as the re-definitions would only be local to thetikzpicture
environment. This is NOT entirely accurate, as it can result in problems inside thetikzpicture
environment, as I just discovered after several hours of debugging.With the wrong thinking that there is no problems in using
\def
within a local scope, I decide to change the hard to read (and hard to modify if additional parameters are added at the beginning) macros such as:to something like this:
thinking that there is no problem if I overwrite
\XAxisMin
within this macro as I don't need what ever has been set previously and it will be restored anyway upon the end of this macro.Well, this is ok in most cases -- but not ok if some parent macro had defined
\XAxisMin
and had passed it to this macro as a parameter. The code below illustrates this. It compiles just fine as is, but if you un comment the lasttikzpicture
thenpdflatex
seems to be stuck in an infinite loop.Test Code:
Code: Problem in using
\def
withintikzpicture
: