PGFPlots – Reading and Processing Data in PGFPlots

pgfplotspgfplotstable

I have a standard text file, two columns, space separated, containing x and y data to be plotted. I want to plot x vs -y, i.e. plot(x,-y).

In general, how do you read your data and plot a function of them in pgfplots, e.g. (x,-y), (log x, y), (x, y^2), etc?

The following code returns error

\pgfplotstableread{inputdata.txt}\mydata;
\addplot table [ color=red, only marks, mark=*, mark size=0.5pt, x expr=\thisrowno{1}, y expr=\thisrowno{2}*-1 ] {\mydata};

Best Answer

You're mixing up the keys for \addplot with those for the table directive.

Try something like:

\documentclass{article}
\usepackage{pgfplotstable}
\pagestyle{empty}
\begin{document}

\begin{tikzpicture}
\begin{axis}[xlabel=$x$,ylabel=$-y$]
\pgfplotstableread{inputdata.txt}\mydata;
\addplot [ 
           color=red, 
           only marks, 
           mark=*, 
           mark size=0.5pt, 
         ]
         table
         [
           x expr=\thisrowno{0}, 
           y expr=\thisrowno{1}*-1 
         ] {\mydata};
\end{axis}
\end{tikzpicture}

\end{document}

Where the data file looks like:

x y
1 2
2 -1 
3 0 
4 2 
5 3 
6 6 

enter image description here

To get other transformations such as (x,y^2), just supply the appropriate expression:

y expr=\thisrowno{1}^2,

There is no log function available, as far as I know, but there is natural log so you can write

x expr=ln(\thisrowno{0}),

Also, instead of using \thisrowno, if you have column headings in the data file (like in the example I gave above), then you can write

x expr=\thisrow{x},
y expr=\thisrow{y},

and then you don't have to worry about the exact column numbering. Or if you had a data file that looks like

input output
1 2
2 -1 
3 0 
4 2 
5 3 
6 6 

You would write

x expr=\thisrow{input},
y expr=\thisrow{output},

Though in this later case, if you're not transforming the data somehow, you could just write

x=input,
y=output,