8

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

\begin{document}
\begin{tikzpicture}
\begin{axis}
\pgfplotstableread{table.tsv}\loadedtable
  \foreach \metavar in {foo,bar} {
    \addplot table[x index=1,y=\metavar] from \loadedtable node {\metavar};
  }
\end{axis}
\end{tikzpicture}
\end{document}

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> 
                 \par 

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?

1 Answers1

6

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

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\pgfplotstableread[row sep=crcr]{
X foo bar\\
1 10 20\\
2 10 30\\
3 20 40\\
}\loadedtable
  \pgfplotsinvokeforeach {foo,bar} {
    \addplot table [x index=0,y=#1] \loadedtable node [anchor=south] {#1};
  }
\end{axis}
\end{tikzpicture}
\end{document}
David Carlisle
  • 757,742
Jake
  • 232,450
  • 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 Sewe Apr 03 '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 03 '12 at 14:03
  • Yes, that did the trick. Thanks for you help. – Andreas Sewe Apr 03 '12 at 14:30