I am trying to use coordinate evaluation ($ ... $) inside a tikz foreach loop to do arithmetic with my loop variable. However, I cannot seem to get it to work.

My code so far:

    \coordinate (A) at (1,1);
    \coordinate (B) at (3,2);
    \coordinate (D) at ($(B)-(A)$);
        grid style={line width=.1pt, draw=gray!10},
        %major grid style={line width=.2pt,draw=gray!50},
        axis lines=middle,
        minor tick num=0,
        axis line style={latex-latex},
        ticklabel style={font=\tiny,fill=white},
        xlabel style={at={(ticklabel* cs:1)},anchor=north west},
        ylabel style={at={(ticklabel* cs:1)},anchor=south west}

    \draw [fill] (A) circle (1.5pt) node [below right] {$P$};
    \draw [fill] (B) circle (1.5pt) node [below right] {$Q$};
    \draw[->,thick,red!60!white] (A) -- (B) node [midway,below right,yshift=2pt] {$\vec d$};

    \foreach \x in {-3,...,6} {
        \draw [fill] ($(A)+\x/3*(D)$) circle (1.5pt);% node [below right] {$P$};


The error seems to be ($(A)+\x/3*(D)$). How is one supposed to do this computation? I have tried defining a new point in my loop with

\path let \p1 = (D) in coordinate (r) at (\x*\x1,\x*\y1);

but that does not work either.


Inside the axis environment foreach does not get expanded properly hence you need to use the appropriate loop

\pgfplotsinvokeforeach{-3,...,6} {
    \draw [fill] ($(A)+#1/3*(D)$) circle (1.5pt);% node [below right] {$P$};

would work.

| improve this answer | |
  • I didn't anticipate the axis environment could be the problem. Thank you! – Jason Siefken Nov 26 '16 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.