3

I am using Texmaker. What's wrong with "x index = \t+1"?

\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\usepackage{filecontents}


\begin{document}

\begin{filecontents}{data.txt}
        1,2,3,4,5
        4,5,6,7,8
\end{filecontents}

\begin{tikzpicture}
        \begin{axis}
            \foreach \t in {1,2,3}
            \addplot+ table [col sep=comma, x index=\t+1, y index=0] {data.txt};
        \end{axis}
\end{tikzpicture}

\end{document}

And it returns the following error message:

Package pgfplots Error: Sorry, the requested column number '1+1' in table 'data.txt' does not exist!? Please verify you used the correct index 0 <= i < N..
5

The expression \t+1 need to be evaluated before being passed to x index.

Usually this can be done with x index/.evaluated=\t+1, but here pgfplots turns on floating-point evaluation inside axis environment, hence the evaluated result of \t+1 would be the floating-point representation of 2.0.

Besides looping from \t = 2, here two extra attempts are provided:

  1. Use a manual calculation with primitive \numexpr: x index/.expanded=\the\numexpr \t+1.
  2. Define a new key .evaluated to int and use it as .evaluated to int=\t+1.
\begin{filecontents}[noheader]{data.txt}
        1,2,3,4,5
        4,5,6,7,8
\end{filecontents}

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}

\makeatletter
\pgfkeys{
  /handlers/.evaluated to int/.code=
    \pgfkeysifdefined{/pgf/fpu/.@cmd}
      {\pgfkeys@mathparse{#1}%
       \pgfmathfloattoint{\pgfmathresult}%
       \expandafter\pgfkeys@exp@call\expandafter{\pgfmathresult}}
      {\pgfkeys@error{You have to load `fpu' to use handler `.evaluated to int'}}
}
\makeatother

\begin{document}
\begin{tikzpicture}
  \begin{axis}
    \foreach \t in {1,2,3}
      \addplot+ table [col sep=comma, x index/.expanded=\the\numexpr\t+1, y index=0] {data.txt};
  \end{axis}
\end{tikzpicture}
\qquad
\begin{tikzpicture}
  \begin{axis}
    \foreach \t in {1,2,3}
      \addplot+ table [col sep=comma, x index/.evaluated to int=\t+1, y index=0] {data.txt};
  \end{axis}
\end{tikzpicture}
\end{document}

enter image description here

1
  • 1
    Many thanks @muzimuzhi Z
    – Lerh
    Jun 18 at 2: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.