Consider this MWE:
\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usetikzlibrary{calc}
\pgfplotstableread[col sep=space,row sep=newline,header=true]{
ts val
0.0 0.0
1.0 1.0
1.1 4.9
2.0 2.0
2.2 4.9
4.8 0.2
}\mytable
\def\drawLines{%
\pgfplotstableforeachcolumnelement{[index]0}\of\mytable\as\cx{%
% \node{I have now cell element ‘\cx’ at row index ‘\pgfplotstablerow’;\par};
\edef\temp{ %
\noexpand\draw[%
draw=black,%
fill=none,%
opacity=0.7,%
] let \noexpand\p1=({axis cs:\cx,0}), \noexpand\p2=({rel axis cs:0,0}),
\noexpand\p3=({rel axis cs:1,1}) in
(\noexpand\x1,\noexpand\y2) -- (\noexpand\x1,\noexpand\y3)
; %
}
\temp
}
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[extra x ticks={3.5}]
\addplot[smooth] table {\mytable};
\addplot[only marks,mark=*,mark options={color=blue}] table {\mytable};
\draw[red] let \p1=(rel axis cs:0,0), \p2=(rel axis cs:1,1), \p3=(axis cs:3.5,0)
in (\x3,\y1) -- (\x3,\y2);
\drawLines % passes no problem
\end{axis}
\drawLines % fails w/ "! Missing \endcsname inserted." \pgfcrdmth@x
\end{tikzpicture}
\end{document}
As it is, it will fail with:
! Missing \endcsname inserted.
<to be read again>
\pgfcrdmth@x
l.42 \drawLines
% fails w/ "! Missing \endcsname inserted." \pgfcrdmth@x
... but if you comment the line, marked with % fails... - then the document compiles successfully, and as expected? So obviously, the \drawLines function, which calls \draw via \pgfplotstableforeachcolumnelement, does work - but only from inside an {axis}, not outside it?
Why does this happen - and how could I get this macro to execute outside of {axis}, while still in {tikzpicture}? How can I otherwise know, which code can be ran from where?
PS: As it is, this looks like Why doesn't a \foreach variable work in \draw in an \axis?, but I'm guessing that question could have been answered with the \edef\temp...\temp thing that I'm using here; which is why this problem puzzles me...

rel axistoaxisin the code above, and it still fails with same message as above - so there is possibly something else here as well? – sdaau Jul 05 '14 at 16:28