2

I am astonished that when I attempt to square a number read from a table with pgfplots, the result has the same sign. Consider this:

\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\begin{filecontents}{data.dat}
   col1 col2
   -1   -2
   0    -2
   2    -3
\end{filecontents}
\begin{document}
\pgfplotstableread[col sep=space]{data.dat}\datatable
\begin{tikzpicture}
   \begin{axis}[
         xtick=data,
      ]
      \addplot table[
         x expr=\coordindex,
         y expr={
            \thisrow{col2}^2
         }
      ] {\datatable};
   \end{axis}
\end{tikzpicture}
\end{document}

enter image description here

col2s values are supposed to get squared \thisrow{col2}^2, but it appears as if \thisrow{col2} expands to e.g. -2 and the expression becomes -2^2 and is parsed as -(2^2). Also the second row seems to be wrong altogether. Is this behaviour intended and where is it documented? I find this grossly counterintuitive.

1 Answer 1

3

TeX expands \thisrow{col2} to -2, so what's eventually seen is

-2^2

which is, according to the usual conventions, -4. The same in the other cases.

Adding parentheses, as follows,

\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\begin{filecontents}{data.dat}
   col1 col2
   -1   -2
   0    -2
   2    -3
\end{filecontents}
\begin{document}
\pgfplotstableread[col sep=space]{data.dat}\datatable
\begin{tikzpicture}
   \begin{axis}[
         xtick=data,
      ]
      \addplot table[
         x expr=\coordindex,
         y expr={
            (\thisrow{col2})^2
         }
      ] {\datatable};
   \end{axis}
\end{tikzpicture}
\end{document}

produces

enter image description here

4
  • What are those usual conventions you speak of? To me this is not intuitive, but that is also not the real point. What I find strange is that \thisrow{..} is not somehow automatically parenthesised. If I attempt to square a value, I would expect it to work on both negative and positive numbers. I am looking for a rationale behind this.
    – oarfish
    Aug 23, 2015 at 14:39
  • @oarfish Math conventions. Keep in mind that TeX does macro expansion, the parsing of expressions is done by PGF at a later stage.
    – egreg
    Aug 23, 2015 at 14:40
  • 1
    @oarfish This is an old issue and discussed with the authors some time ago on the TikZ/PGF Sourceforge bug report And as egreg mentioned power operation has a priority over negation as a convention unless a grouping with brackets is used.
    – percusse
    Aug 23, 2015 at 14:47
  • 1
    @oarfish is right, the convention to merely expand in text-form is not intuitive. I as author of pgfplots will address this issue eventually. Thanks for the report. Aug 23, 2015 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.