# extracting coordinates from “position” pair in tikz

I think I have a simple problem but somehow I'm unable to find any solution: I have the following code:

\begin{tikzpicture}[scale=1 , auto,swap]
\foreach \pos/\name in { {(9,7)}/a, {(6,6)}/b, {(9,5)}/c }{
\node (\name) at \pos {\pos};
}
\end{tikzpicture}


It obviously doesn't work as intended because \pos produces labels like (9,7):)

Is there a simple way to extract the first coordinate from \pos? So that labels of node would be 9,6,9 respectively?

And I would like to avoid changing entire loop to something like

\foreach \posX/\posY/\name in { {9/7/a}, {6/6/b}, {9/5/c} }{...}

• leave the slashes outside the braces e.g. {(9,7)}/a – percusse Mar 19 '13 at 16:43
• You can extract the coordinates using let...in syntax, but unfortunately you'll get the result in points, not in the "unit-less" integers you specified them. – JLDiaz Mar 19 '13 at 17:07
• FWIW, you can use let if you replace your \node command for, say, \path let \p1 = \pos in node (\name) at \pos {\x1} to see what @JLDiaz meant. I think you might just have to change your loop, since then the solution would be trivial. – jja Mar 19 '13 at 17:13
• See this answer for a way to extract coordinates from a point already plotted (I know that's not what you're asking). – Ryan Reich Mar 19 '13 at 17:29

Extracting the numbers you put in a pair of coordinates is not possible, because tikz tranforms those "unitless" coordinates into actual points (taking into account the scale, x and y options, etc).

The syntax let...in allows you to get those coordinates, but usually only for using them as part of the calculations to get other coordinates, but not for printing them. Trying to do so:

\usetikzlibrary{calc}
\begin{tikzpicture}[scale=1 , auto,swap]
\foreach \pos/\name in { {(9,7)}/a, {(6,6)}/b, {(9,5)}/c }{
\path let \p1=\pos in node (\name) at \pos {\x1};
}
\end{tikzpicture}


Produces unsatisfactory results: For this particular case, instead of trying to get the X coordinate from tikz, you can try the following hack, which extracts the first number before the comma directly from the \pos macro:

\begin{tikzpicture}[scale=1 , auto,swap]
\def\getX(#1,#2){#1}
\foreach \pos/\name in { {(9,7)}/a, {(6,6)}/b, {(9,5)}/c }{
\node (\name) at \pos {\expandafter\getX\pos};
}
\end{tikzpicture}


Resulting in what you want: • I was hacking away at a solution with xstring, but this is much nicer. :) – jja Mar 19 '13 at 17:28
• \foreach \pos/\name[evaluate={\tX=\expandafter\getX\pos}] in {(9,7)/a, (6,6)/b, (9,5)/c} \node (\name) at \pos {\tX}; might be helpful if you want to use the values repeatedly. (Or, of course, \edef\tX{\expandafter\getX\pos}.) – Qrrbrbirlbel Jul 26 '13 at 12:34