# How to node foreach value in math equation?

I'm trying to plot roots of $(-1)^{n}$. The code works fine

\documentclass[9pt]{article}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}

\def \n {7}

\begin{center}
\begin{tikzpicture}[scale=1.2,font=\tiny]
\begin{axis}[
axis x line=middle,
axis y line=middle,
domain=-8:8,
restrict y to domain=-8:8,
x=3cm,
y=3cm,
xmin=-1.5,
ymin=-1.5,
xmax=1.5,
ymax=1.5,
grid=both,
xtick={-3,-2.75,...,3},
ytick={-3,-2.75,...,3},
]
({cos(t*180/pi)},{sin(t*180/pi)});
\foreach \k in {1,...,\n}{
{\t*cos(\k*360/\n)+(1-\t)*cos((\k+1)*360/\n)},
{\t*sin(\k*360/\n)+(1-\t)*sin((\k+1)*360/\n)}
);
({1.1*cos(\k*360/\n)},{1.1*sin(\k*360/\n)})
node {\Large $w^{\k}$};
}
\end{axis}
\end{tikzpicture}
\end{center}

\end{document}


but it doesn't recognize this part

\addplot[mark=none] ({1.1*cos(\k*360/\n)},{1.1*sin(\k*360/\n)}) node {\Large $w^{\k}$};}

• What do you mean "doesn't recognize". Is there an error? Is the output not what you expect? Thanks :-) – darthbith Feb 14 '15 at 11:46
• @darthbith That's what a MWE is for :) – percusse Feb 14 '15 at 11:58
• @percusse Well, yes, but a clear description of the actual problem always helps too, and helps people searching in the future to find it! But I see you've divined the intent of the question :-) – darthbith Feb 14 '15 at 11:59
• @darthbith Also true but if I know what my problem is, probably I would solve it myself heheh. – percusse Feb 14 '15 at 12:01

This is a very common problem in disguise namely the accumulation of plots and untimely expansion. pgfplots first reads and accumulates all the plot commands and after some analysis starts drawing. Because simple foreach loop scopes its contents when pgfplots start unpacking the plot commands it doesn't remember that \k was the loop variable and takes it literal as TeX \k character.

pgfplots offers two additional foreach loops for this and you can check the manual for different purposes.

Here if you modify your loop as follows, pgfplots first expands the variables at the time of encounter and stores the actual values (#1 denotes the loop variable in this context)

\pgfplotsinvokeforeach{1,...,\n}{
node {\Large $w^{#1}$};