I have some spectra to plot, which I exported from the Siemens Xray toolbox, which works nicely with pgfplots.
Since these are multiple files that look the same I think I can do it with a for loop, which also works.
But now I have problems with adding a legend entry, since that does not work. When I use a \addlegendentry with siunitx I cannot compile the copde below, I get informed that the
Argument of \add@accent has an extra }.
This becomes more clear when I don't use siunitx but just want to get the values (commented line in the example below), then there's no number in the legend, only a nice k with a hat (no idea how it's called :)).
When I don't do use a for-loop, but add the plots manually for each one it works. But since in the final figure I have to plot more than 20 spectra (all much bigger than the one in the example) I'd like to do it in a loop, ideally.
\documentclass{article}
\usepackage{siunitx}
\usepackage{pgfplots}
\usepackage[active,tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\usepackage{filecontents}
\begin{filecontents*}{Xray-Spectrum_040.txt}
9 2.23512e-015
10 2.18948e-009
\end{filecontents*}
\begin{filecontents*}{Xray-Spectrum_046.txt}
9 1.98718e-015
10 1.56485e-009
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\foreach \v in {40,46} {
\addplot table {Xray-Spectrum_0\v.txt};
\addlegendentry{\v kv}
}
\end{axis}
\end{tikzpicture}
\end{document}
Related
I had to rename the files from Xray-Spectrum_046kV.txt to Xray-Spectrum_046.txt to make it work. Is there a way I can get the variable to be evaluated in the middle of the filename?

addlegendentryexpanded{}instead. See also https://tex.stackexchange.com/a/317015/1280 – Flow Aug 21 '19 at 13:00