Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I'm having a pretty weird issue with TikZ and pgfplots. I want to have a legend driven by a \foreach variable, but TikZ won't let me do that. I tried a couple of different stuff and realized that \foreach doesn't seem to work inside the axis environment.

For instance the following code compiles

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

    \begin{tikzpicture}
    \foreach \x/\y in {1/A,2/C,3/D} 
{
\draw (\x,-4pt) -- (\x,4pt) node [below,yshift=-2ex] {\y};
}
    \begin{axis}
    \addplot   {sin(deg(x))};
    \addlegendentry{2}
    \end{axis}
    \end{tikzpicture}

    \end{document}

And this code doesn't

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

    \begin{tikzpicture}
    \begin{axis}
    \foreach \x/\y in {1/A,2/C,3/D} 
{
\draw (\x,-4pt) -- (\x,4pt) node [below,yshift=-2ex] {\y};
}
    \addplot   {sin(deg(x))};
    \addlegendentry{2}
    \end{axis}
    \end{tikzpicture}

    \end{document}
share|improve this question

1 Answer 1

up vote 4 down vote accepted

You could modify the way of expansion in the axis environment like described here by Christian. This compiles:

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

\begin{tikzpicture}
\begin{axis}
\foreach \x/\y in {100/A,200/C,300/D} 
{
  \edef\temp{\noexpand\draw (\x,-4pt) -- (\x,4pt) node [below,yshift=-2ex] {\y};}
  \temp
}
\addplot   {sin(deg(x))};
\addlegendentry{2}
\end{axis}
\end{tikzpicture}

\end{document}

There's still some fine tuning of values required. Though I recommend using pgfplot's features instead of \foreach, such as \pgfplotsforeachungrouped for example.

share|improve this answer
    
thanks stefan. I tried \pgfplotsforeachungrouped as well but it didn't work, so I had to choose your option. –  ben paillard Jul 31 '11 at 19:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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