TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a (multi)line plot generated from a table in pgfplots:

  \foreach \metavar in {foo,bar} {
    \addplot table[x index=1,y=\metavar] from \loadedtable node {\metavar};

This works well except for the node I want to place at the end of each line as a kind of inline legend.

Here, LaTeX complains:

! Argument of \T1\metavar has an extra }.
<inserted text> 

If I substitute the \metavar node label with some literal text, everything compiles fine, but this of course misses the point of the \foreach. So how do I access a loop variable in a place like this?

share|improve this question
Feels like a duplicate of this one here but I'm not sure – percusse Apr 2 '12 at 17:35
Related Question PGFplots foreach equivalent to TikZ's with multiple variables separated by a slash which has a good explanation of the issue here. – Peter Grill Apr 2 '12 at 17:48
@Andreas: When posting code examples like yours, it's usually a good idea to make them complete and compilable (i.e. include \documentclass and all packages that are necessary), and self-sufficient (in this case, that would mean including dummy data). That saves people who try to help the effort of having to complete the code themselves first. – Jake Apr 2 '12 at 17:48
@Jake: Sorry. Will post complete examples from now on. – Andreas Apr 3 '12 at 10:53
up vote 4 down vote accepted

In this case, you'll have to use the \pgfplotsforeachungrouped, which makes sure that the loop is not executed inside its own group.

\pgfplotstableread[row sep=crcr]{
X foo bar\\
1 10 20\\
2 10 30\\
3 20 40\\
  \pgfplotsinvokeforeach {foo,bar} {
    \addplot table [x index=0,y=#1] \loadedtable node [anchor=south] {#1};
share|improve this answer
Unfortunately, this doesn't work for me (using the pgfplots that shipped with TeX Live 2011); both lines are labelled "bar". (Also, using \pgfplotsinvokeforeach exhibits this behaviour.) – Andreas Apr 3 '12 at 10:31
@Andreas: Sorry, you're right, \pgfplotsforeachungrouped didn't fix the problem. For me, \pgfplotsinvokeforeach does, however. Can you try with the edited code in my answer? – Jake Apr 3 '12 at 14:03
Yes, that did the trick. Thanks for you help. – Andreas Apr 3 '12 at 14:30

Your Answer


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.