[Tex/LaTex] Problems with \pgfplotstableread and relative paths

errorspathspgfplotstablestandalonetikz-pgf

I have this folder structure in my project:

  • main.tex
  • mystyle.sty
  • tex
    • mytex.tex
  • img
    • myimg.tex
  • dat
    • mydat.dat

And the following files:

main.tex:

\documentclass{scrartcl}
\usepackage{mystyle}

\begin{document}
  \input{tex/mytex}
\end{document}

mytex.tex:

\begin{figure}[ht]
  \centering
  \input{img/myimg.tex}
\end{figure}

myimg.tex:

\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\IfStandalone{
  \newcommand{\fromRoot}[1]{../dat/#1}
}{
  \newcommand{\fromRoot}[1]{./dat/#1}
}
\pgfplotstableread{\fromRoot{mydat.dat}}\datatable
\begin{document}
  \begin{tikzpicture}
    \begin{axis}[width=10cm, height=6cm]
      \addplot table[x=0,y=1]{\datatable};
    \end{axis}
  \end{tikzpicture}
\end{document}

mydat.dat:

1 0.4032
2 0.40241
3 0.38704

mystyle.sty:

\ProvidesPackage{mystyle}

\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

In my understanding should the path to the mydat.dat file be ./dat when I'm compiling the main file main.tex. But I always get the error message:

(./img/myimg.tex
! Undefined control sequence.
\pgfplotstableread@filename ^^@-\datatable

Best Answer

By default, standalone removes all preambles (i.e. everything before \begin{document}) from the included .tex files, which is why \datatable isn't defined in the main document. You can either load \usepackage[subpreambles]{standalone} in your main.tex to include the preamble from mytex.tex, or you could move the macro after \begin{document}.