26

For example I would like to do something like this

r=2
\begin{tikzpicture}
    \draw (0,{2*r}) ellipse ({sqrt(r)} and {8/r});
    \draw (0,{r}) ellipse ({sqrt(r/2)} and {4/r});
\end{tikzpicture}

Where everywhere r is seen in the above tikz commands, it is replaced by its defined value. I cannot seem to find a way to conveniently do this, I am sure I am just not looking in the right place

2 Answers2

28

One option, \defining \ra:

\documentclass{article} 
\usepackage{tikz}

\begin{document} 

\def\ra{2}
\begin{tikzpicture}
    \draw (0,{2*\ra}) ellipse ({sqrt(\ra)} and {8/\ra});
    \draw (0,{\ra}) ellipse ({sqrt(\ra/2)} and {4/\ra});
\end{tikzpicture}

\end{document}

enter image description here

You could use instead a (La)TeX length, via \newlength, \setlength and the appropriate syntax for lengths operations but using a length register for this simple application is not really necessary.

Gonzalo Medina
  • 505,128
  • 2
    Note on \def, it does roughly speaking "text substitution" so if you have e.g. \def\a{1+2} \def\b{\a*2} prepare for surprises. Also the value is recomputed every time, use pgfmathsetmacro is better – user202729 May 15 '22 at 03:23
18

Or go the pgf way by defining

\pgfmathsetmacro{\ra}{2}

Code:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\pgfmathsetmacro{\ra}{2}
\begin{tikzpicture}
    \draw (0,{2*\ra}) ellipse ({sqrt(\ra)} and {8/\ra});
    \draw (0,{\ra}) ellipse ({sqrt(\ra/2)} and {4/\ra});
\end{tikzpicture}

\end{document}

enter image description here

You can also use pgfkeys for this.

\documentclass{article}
\usepackage{tikz}
\pgfkeys{/tikz/.cd,
  ra/.store in=\ra,
  ra=0   %% initial value, set to anything so that even if you don't specify a value later, it compiles
   }

\begin{document}
\begin{tikzpicture}[ra=2]   %% set it here, if not set, initial value 0 is taken
    \draw (0,{2*\ra}) ellipse ({sqrt(\ra)} and {8/\ra});
    \draw (0,{\ra}) ellipse ({sqrt(\ra/2)} and {4/\ra});
\end{tikzpicture}

\end{document}
  • 1
    Note that \pgfkeys{/tikz/.cd, ra/.store in=\ra, ra=0} can be shortened as \tikzset{ra/.store in=\ra, ra=0}. For other packages based on pgfkeys, the path before .cd in your solution or the shortcut command I just mentioned generally needs to be adapted (otherwise, problems as shown here may arise). For example, with pgfplots, one would use either \pgfkeys{/pgfplots/.cd, ra/.store in=\ra, ra=0} or \pgfplotsset{ra/.store in=\ra, ra=0}. The version with \pgfplotsset is probably more “idiomatic.” – frougon Aug 26 '19 at 06:34