Define a variable in TikZ

\begin{tikzpicture} 
\coordinate (A) at (2,3);
\coordinate (B) at (2,5);
\draw[->] (A)--(B) ;
\end{tikzpicture}

You can add

\newcommand\XA{2} etc. and then \coordinate (A) at (\XA,\YA);


I'm using \def\x{1068} to have x as a variable in my script to generate scalebars onto images with TikZ. That works like a charm for me.

A working example is pasted below, even though the image does not look very nice :)

\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{tikz}
\usepackage{siunitx}
\usepackage[graphics,tightpage,active]{preview}
\PreviewEnvironment{tikzpicture}
\newcommand{\imsize}{\linewidth}
\newlength\imagewidth % needed for scalebars
\newlength\imagescale % ditto
\begin{document}%
%-------------
\pgfmathsetlength{\imagewidth}{\imsize}%
\pgfmathsetlength{\imagescale}{\imagewidth/1728}%
\def\x{1068}% scalebar-x at golden ratio of x=1728px
\def\y{320}% scalebar-y at 90% of height of y=356px
\def\shadow{11}% shadow parameter for scalebar
\begin{tikzpicture}[x=\imagescale,y=-\imagescale]
\clip (0,0) rectangle (1728,356);
    \node[anchor=north west, inner sep=0pt, outer sep=0pt] at (0,0) {\includegraphics[width=\imagewidth]{image}};
    % 279px = 1.7819mm > 100px = 638um > 78px = 500um, 16px = 100um
    \draw[|-|,blue,thick] (791,151) -- (1020,311) node [sloped,midway,above,fill=white,semitransparent,text opacity=1] {\SI{1.7819}{\milli\meter} (1204px) TEMPORARY!};
\draw[|-|,thick] (\x+\shadow,\y+\shadow) -- (\x+78+\shadow,\y+\shadow) node [midway, above] {\SI{500}{\micro\meter}};
    \draw[|-|,white,thick] (\x,\y) -- (\x+78,\y) node [midway,above] {\SI{500}{\micro\meter}};
    \draw[color=red, anchor=south west] (0,356) node [fill=white, semitransparent] {Legend} node {Legend};
\end{tikzpicture}%
%-------------
\end{document}%

Tikz offers a powerful solution to dealing with variables through the library math (TikZ version >= 3.00)

\documentclass{article}
\usepackage{tikz}
\begin{document}

\usetikzlibrary{math} %needed tikz library

% Variables must be declared in a tikzmath environment but
% can be used outside (almost anywhere)
% Do not forget SEMICOLONS after each command (!)
\tikzmath{\x1 = 1; \y1 =1; 
% Computations are also possible
\x2 = \x1 + 1; \y2 =\y1 +3; } 

% Using the variables for drawing
\begin{tikzpicture}
    \draw[very thick, -stealth] (\x1, \y1)--(\x2, \y2);
\end{tikzpicture}

% Using the variables in math and text modi
The coordinates of the second point are:

$x_2 = \x2$ and $y_2 =$ \y2

% Note that the name of the variables, e.g., \x1, can contain a number (!)
% That would be not allowed with a \newcommand definition
\end{document}

The result of the code above

See also this answer for more examples with different uses.

Tags:

Tikz Pgf