# How to read value from table, assign to variable and use it in x expr=\thisrow{}

How can I read the first value from the first column of a table, assign it to a variable and the use it in some math expression with x expr=\thisrow{}?

The code would be something like this, but in my example I'm manually typing the first value of the first column (3 in this example, as in x expr=\thisrow{time}-3) and I would like it to be done automatically.

UPDATE: My real table has between 5 and 6 columns and some thousands of rows. Please, this should be taken into account for the solution.

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

\begin{filecontents}{data.dat}
time speed
3 5
4 3
5 6
6 4
7 0
8 1
\end{filecontents}

\begin{document}

\begin{tikzpicture}
\begin{axis}[xlabel=time,ylabel=speed]
\end{axis}
\end{tikzpicture}

\end{document}

-
You could read the element before you start the axis environment and save it to a macro using \pgfplotstablegetelem{0}{time}\of{data.dat} \edef\firstrowvalue{\pgfplotsretval}. Then you can access it in your plot using x expr=\thisrow{time}-\firstrowvalue. Is that what you're looking for, or do you want an even more automatic solution (something like a \firstrow{<column name>} thata can be used directly in x expr, for example)? – Jake Jan 17 '13 at 7:14
I believe this solution would work for me. But I always get an error when I use pgfplotstable complaining about the size of the table. My real table is much bigger than that (thousands of rows) and 5--6 columns. From pgfplots manual section 4.2.3 > "1. If tables contain few rows and many columns, the ⟨\macro⟩ framework will be more efficient. 2. If tables contain more than 200 data points (rows), you should always use file input (and reload if necessary)." I believe number 2 is my case. – perr0 Jan 17 '13 at 11:44

If you use \addplot file instead of \addplot table, you can't use x expr or \thisrow or column names, because file expects a very simple two column layout. In this case, you could work with an x filter that checks whether its currently processing the first coordinate, and if it is, it saves the value to a global macro, which is then subtracted from all other coordinates:

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

\begin{filecontents}{data.dat}
#time speed
3 5
4 3
5 6
6 4
7 0
8 1
\end{filecontents}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
xlabel=time,ylabel=speed,
x filter/.code={
\ifnum\coordindex=0
\xdef\firstvalue{\pgfmathresult}
\fi
\pgfmathparse{\pgfmathresult-\firstvalue}
}]

@perr0: Can you plot your file successfully using \addplot table? – Jake Jan 17 '13 at 12:51
Yes, I can plot all five columns using \addplot table. – perr0 Jan 17 '13 at 12:56
@perr0: No, it looks like \pgfplotstablegetelem is stumbling over the column separator of the table. Could you post the first two lines of your table? – Jake Jan 17 '13 at 13:25