Graph from csv table (col sep=comma) with pgfplotsinvokeforeach
1,069
What caused the error is, that you also missed to add col sep=comma
to the \pgfplotsread
command. (Besides that, I further "optimized" the code a bit.)
% used PGFPlots v1.16
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents}{testdata.dat}
,Distance,Velocity,Something
0,0,1,0.2
1,1,1,0.3
1.5,1.999,1,0.4
2,2,0,0.4
3,2,0,0.5
\end{filecontents}
\newcommand{\plotfile}[1]{
\pgfplotstableread[col sep=comma]{#1}{\table}
\pgfplotstablegetcolsof{\table}
\pgfmathtruncatemacro\numberofcols{\pgfplotsretval-1}
\pgfplotsinvokeforeach{1,...,\numberofcols}{
\pgfplotstablegetcolumnnamebyindex{##1}\of{\table}\to{\colname}
\addplot table [y index=##1] {\table};
\addlegendentryexpanded{\colname}
}
}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\plotfile{testdata.dat}
\end{axis}
\end{tikzpicture}
\end{document}
Related videos on Youtube
Author by
Spenhouet
Updated on August 01, 2022Comments
-
Spenhouet over 1 year
I have many huge csv files and need a easy way to plot all of them without defining headers etc. every time.
Therefore I found this: https://tex.stackexchange.com/a/24023/95657
That is exactly what I need but it doesn't work for csv files with comma separation.
The data isn't shown correct.
MWE:
\documentclass{article} \usepackage{pgfplots} \usepackage{filecontents} \begin{filecontents}{testdata.dat} ,Distance,Velocity,Something 0,0,1,0.2 1,1,1,0.3 1.5,1.999,1,0.4 2,2,0,0.4 3,2,0,0.5 \end{filecontents} \newcommand{\plotfile}[1]{ \pgfplotstableread[col sep=comma]{#1}{\table} \pgfplotstablegetcolsof{#1} \pgfmathtruncatemacro\numberofcols{\pgfplotsretval-1} \pgfplotsinvokeforeach{1,...,\numberofcols}{ \pgfplotstablegetcolumnnamebyindex{##1}\of{\table}\to{\colname} \addplot table [col sep=comma, y index=##1] {#1}; \addlegendentryexpanded{\colname} } } \begin{document} \begin{tikzpicture} \begin{axis}[legend pos=north west] \plotfile{testdata.dat} \end{axis} \end{tikzpicture} \end{document}
What do I need to do to get this to work?
-
Spenhouet about 5 yearsNice! That works
-
Stefan Pinnow about 5 yearsYou are welcome. If you like my answer and it was helpful, please consider upvoting (by clicking on the arrows next to the score) and/or marking it as the accepted answer (by clicking on the checkmark ✓).
-
Spenhouet about 5 yearsSure, I would have done anyway (just have to wait 5 minutes after asking to accept an answer).
-
Stefan Pinnow about 5 years*g, ok, learned something new today :)