pgfplots foreach 语法列索引中的错误

pgfplots foreach 语法列索引中的错误

我在用纺织机械商. 有什么问题“x 索引 = \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}

并返回以下错误消息:

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..

答案1

该表达式\t+1在传递给之前需要进行评估x index

通常这可以用 来完成x index/.evaluated=\t+1,但这里pgfplots打开环境内部的浮点评估axis,因此 的评估结果\t+1将是 的浮点表示2.0

除了从 循环之外\t = 2,这里还提供了两次额外的尝试:

  1. 使用原始的手动计算\numexprx index/.expanded=\the\numexpr \t+1
  2. 定义一个新键.evaluated to int并将其用作.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}

在此处输入图片描述

相关内容