5

I have used variable \x while drawing nodes using TiKZ. The drawing part works well without any problems. I have also added keys to the nodes so that they can be linked later. I am facing a curious problem. The node key works if the \x is a whole number, but doesn't work if it is a decimal.

For example, in the code below, I am using the key as \x g2y.

\fill[fill=yellow]
\foreach \x in {2.5,7,11.5} 
{ (\x,10) circle(.45) node(\x g2y) {}};

Now when I try to use the keys from here, only the key with \x value 7 works. For other values of \x like 2.5 and 11.5 it gives an error:

ERROR: Package pgf Error: No shape named 2 is known.

Somehow, the entire decimal value of the number is not being passed to the key, only the whole number before the decimal. How can this be resolved?

enter image description here

MWE is appended below:

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

\begin{tikzpicture}[scale=.5]

\fill (9,13.5)[fill=yellow] circle(.5) node (g1){};

 \fill[fill=yellow]
 \foreach \x in {2.5,7,11.5} 
 { (\x,10) circle(.45) node(\x g2y) {}};
% works here with only 7
\draw [red!50,thick]\foreach \x in {7}
 {(g1)--(\x g2y)};

% doesn't works here with 2.5 and 11.5
% \draw [red!50,thick]\foreach \x in {2.5,7,11.5} 
% {(g1)--(\x g2y)};

\end{tikzpicture}
\end{document}
1

1 Answer 1

7

The problem is that TikZ uses . to access an anchor of a node, for example a.west. So when you have a node called 2.5g2y, and use that in a \draw, TikZ thinks that is a node called 2, and the anchor would be 5g2y.

I don't know if it's possible to use periods in node names, but a workaround is to add a count to your loop, and use that value instead.

Unrelated comment: in general the minimal class should be avoided, see Why should the minimal class be avoided?

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

\begin{tikzpicture}[scale=.5]

\fill (9,13.5)[fill=yellow] circle(.5) node (g1){};

 \fill[fill=yellow]
 \foreach [count=\i] \x in {2.5,7,11.5} 
 { (\x,10) circle(.45) node(\i g2y) {}};

\draw [red!50,thick]\foreach \x in {1,2,3}
 {(g1)--(\x g2y)};

\end{tikzpicture}
\end{document}
1
  • Thanks for the workaround. Have updated the MWE with article class.
    – Damitr
    Jun 21, 2017 at 7:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .