# Grouping data in pgfplots

I have a file with measurement results for different settings (group) in a single csv file as shown below. I would like to plot a line in pgfplots for each group and provide an appropriate legend. Is there a way to automate the process shown below? That is, automatically recognizing which groups exist in the data and adding a line as well as a legend entry for each group.

\documentclass{minimal}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents*}{data.csv}
group, x,  y
1.10,  1,  3.5
1.10,  2,  2.2
1.10,  3,  2.1
1.10,  4,  1.5
2.12,  1,  4
2.12,  2,  3
2.12,  3,  2
2.12,  4,  1
3.21,  1,  2
3.21,  2,  2.2
3.21,  3,  2.4
3.21,  4,  2.6
\end{filecontents*}

\begin{document}
\begin{tikzpicture}

\pgfplotsset{
discard if not/.style 2 args={
x filter/.code={
\edef\tempa{\thisrow{#1}}
\edef\tempb{#2}
\ifx\tempa\tempb
\else
\def\pgfmathresult{inf}
\fi
}
}
}

\begin{axis}
\addplot table [discard if not={group}{1.10}, x=x, y=y, col sep=comma] {data.csv};
\addplot table [discard if not={group}{2.12}, x=x, y=y, col sep=comma] {data.csv};
\addplot table [discard if not={group}{3.21}, x=x, y=y, col sep=comma] {data.csv};
\legend{1,2,3}
\end{axis}
\end{tikzpicture}
\end{document}


• It already looks automated to me. What would be the extra bit? – percusse Sep 2 '15 at 9:16
• oh, and this has nothing to do with a csv formatted file, I have removed the tag (csv=comma separated) – zeroth Sep 2 '15 at 9:39
• I hope the edit clarifies it a little bit. I have also added commas. – koalo Sep 2 '15 at 9:56
• For others information, the scatter/classes method will currently not plot lines in their respective class system. Hence that answer is not viable. – zeroth Sep 2 '15 at 10:11
• @koalo did you find a solution for this? I have exactly the same issue: given a group column in my data file add a separate plotted line for each unique value of the group column. Sounds like something a \foreach plus filtering could do but I don't know how. – Alex Trueman Feb 28 '17 at 17:43

Maybe a \foreach?

\begin{document}
\begin{tikzpicture}
\begin{axis}
\foreach\g in{1.10,2.12,3.21}{
\addplot table [discard if not={group}{\g}, x=x, y=y, col sep=comma] {data.csv};
}
\legend{1,2,3}
\end{axis}
\end{tikzpicture}
\end{document}


• That is a good first step, but you still have to specify every group explicitly. – koalo Mar 29 '17 at 6:00
• @Koalo Good point. I guess there is a method to obtain a non-repeated list of entries that shows up in an pgfplotstable. If not, you can ask a new one! – Symbol 1 Mar 29 '17 at 21:08