19

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};
3
  • Welcome at tex.sx! Does your data file contain empty lines? Commented Jul 7, 2013 at 16:28
  • 1
    The column indexing starts at 0, so most likely you just have to change your expressions to use \thisrowno{0} and \thisrowno{1}
    – Jake
    Commented Jul 7, 2013 at 16:29
  • 1
    @Chris. Hey, this pgfplots is a sweet package! After using gnuplot for a while, now I am converting all my figures to pgfplots. As far as I can tell, it's the way to go for high quality plotting.
    – eli
    Commented Jul 7, 2013 at 17:52

1 Answer 1

27

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,
1
  • Got it! As you all pointed out, the error was that 1) column indices start with 0 ( C style) 2) addplot and table keys were mixed up.
    – eli
    Commented Jul 7, 2013 at 17:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .