1

Consider this MWE:

enter image description here

\documentclass{article}
\usepackage{tikz,pgfplots}
\usepackage{pgfkeys}
\usepackage{xparse}
\usepackage{filecontents}

% DATA 1
\begin{filecontents*}{data1.txt}
1 1
2 4
3 9
4 16
5 25
\end{filecontents*}

% DATA 2
\begin{filecontents*}{data2.txt}
1 15
2 10
3 7
4 5
5 2
6 1
\end{filecontents*}

% see https://tex.stackexchange.com/questions/393622/using-key-values-in-newdocumentcommand
\pgfkeys{/myplot/.is family, /myplot,
    filename/.initial=data.txt,
    linecolor/.initial=black,
}
\newcommand\myplotvals[1]{\pgfkeysvalueof{/myplot/#1}}

\NewDocumentCommand\myplot{m} {
    \begin{tikzpicture}
    \pgfqkeys{/myplot}{#1}% keep key changes local
        \begin{axis}
        \addplot [\myplotvals{linecolor},mark=none] table {\myplotvals{filename}};
        \end{axis}
    \end{tikzpicture}
}


\begin{document}

\myplot{filename=data1.txt,linecolor=red}

\end{document}

Using pgfkeys I've created a command called \myplot which takes data from a .txt as an input and you can optionally set the line color.

This works well for 1 data set. My question is, does anyone know how I could adapt this method to allow adding multiple data sets.

In my MWE, I've included a second data set called data2.txt. What I want the command to do is essentially generate something like this:

\begin{tikzpicture}
\begin{axis}
\addplot [red,mark=none] table {data1.txt};
\addplot [blue,mark=none] table {data2.txt};
\end{axis}
\end{tikzpicture}

Basically, it would be great if I could specify a second .txt file (or potentially n text files) and it would automatically add more \addplot commands as required. Is this even possible to do? I don't know what the input would have to look like, maybe something like \myplot{filename={data1.txt,data2.txt},linecolor={red,blue}} ? But perhaps that doesn't work?

Update

Just to be clear, although in my MWE the file names are sequential, in my real example the file names do not iterate numerically. Therefore I have to specify each file name individually.

  • pgfplots already has cycle lists to deal with the color list so all you need is to rewrite the command in such a way that it loops over file names, which is straightforward. – marmot May 20 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.