10

How can I say sum multiple columns of a table using y expr while also using \foreach

I was hoping something like this would work but apparently it requires some sort of expression evaluation I can't get to work:

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}

\begin{document}
\begin{tikzpicture}
\begin{axis}
    \foreach \y in {1,3,5,7}
        \addplot table[x=Foo, y expr={\thisrowno{\y} + \thisrowno{\y+1}}] {data.csv};
\end{axis}
\end{tikzpicture}
\end{document}

The data:

Foo John John_a Paul Paul_a George George_a Ringo Ringo_a
1 0.0 37.0 0.00 9.00 0.0 4.0 0.0 12.80
2 16.0 5.0 4.0 1.0 0.6 2.80 0.0 12.80
4 8.0 5.0 2.0 1.0 0.3 2.8 0.0 12.80
8 4.0 5.0 1.0 1.0 0.4 2.8 0.0 12.80
16 2.0 5.0 1.2 1.0 0.4 2.8 0.0 12.80
32 1.0 5.0 1.3 1.0 0.5 2.8 0.0 12.80
John
  • 579

2 Answers2

10

Within an axis environment, you'll need to use \pgfplotsinvokeforeach instead of the normal \foreach.

Note that you'll need to evaluate the sum (\y+1 in your example) explicitly, e.g. using \the\numexpr:

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}

\usepackage{filecontents}

\begin{filecontents}{data.csv}
Foo John John_a Paul Paul_a George George_a Ringo Ringo_a
1 0.0 37.0 0.00 9.00 0.0 4.0 0.0 12.80
2 16.0 5.0 4.0 1.0 0.6 2.80 0.0 12.80
4 8.0 5.0 2.0 1.0 0.3 2.8 0.0 12.80
8 4.0 5.0 1.0 1.0 0.4 2.8 0.0 12.80
16 2.0 5.0 1.2 1.0 0.4 2.8 0.0 12.80
32 1.0 5.0 1.3 1.0 0.5 2.8 0.0 12.80     
\end{filecontents}

\begin{document}
\begin{tikzpicture}
\begin{axis}
    \pgfplotsinvokeforeach{1,3,5,7}{
        \addplot table[x=Foo, y expr={\thisrowno{#1} + \thisrowno{\the\numexpr #1+1}}] {data.csv};
        }
\end{axis}
\end{tikzpicture}
\end{document}
Jake
  • 232,450
8

As an alternative to Jake's solution, you can use \foreach's evaluate key, as shown below.

enter image description here

\documentclass{article}
\usepackage{filecontents}

\begin{filecontents*}{data.csv}
Foo John John_a Paul Paul_a George George_a Ringo Ringo_a
1 0.0 37.0 0.00 9.00 0.0 4.0 0.0 12.80
2 16.0 5.0 4.0 1.0 0.6 2.80 0.0 12.80
4 8.0 5.0 2.0 1.0 0.3 2.8 0.0 12.80
8 4.0 5.0 1.0 1.0 0.4 2.8 0.0 12.80
16 2.0 5.0 1.2 1.0 0.4 2.8 0.0 12.80
32 1.0 5.0 1.3 1.0 0.5 2.8 0.0 12.80
\end{filecontents*}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}

\begin{document}
\begin{tikzpicture}
\begin{axis}
    \foreach[evaluate=\y as \ynext using int(\y+1)] \y in {1,3,5,7}
        \addplot table[x=Foo, y expr={\thisrowno{\y}+\thisrowno{\ynext}}] {data.csv};
\end{axis}
\end{tikzpicture}
\end{document}
jub0bs
  • 58,916