嘗試根據 x 值過濾點時 x 過濾器出現問題

嘗試根據 x 值過濾點時 x 過濾器出現問題

我正在嘗試根據其 x 值過濾點。資料可能來自表格格式的文字文件,或直接輸入座標{...}。我嘗試使用 x filter/.code,但對於文字檔案中的資料似乎沒問題,而如果資料直接透過座標{...}鍵入,則相同的程式碼會產生編譯錯誤。

\addplot[scatter, only marks] table[x=xx, y=yy, col sep=comma]{tmp.txt}; 
% Seems working

\addplot[scatter, only marks] coordinates{(0,0) (1,1) (1,1.5) (2,2)}; 
%|16 error| Missing = inserted for \ifnum. Y ...s] coordinates{(0,0) (1,1) (1,1.5) (2,2)};

我懷疑這可能是我在 x 過濾器中使用 \pgfmathresult 時出現的問題,但不確定如何修復。以下是 MWE 以及編譯錯誤。假設檔案 tmp.txt 是:

xx, yy
0,0 
1,1 
1,1.5 
2,2 

代碼是:

\documentclass{article}
\usepackage{pgfplots}   

\begin{document}

\begin{tikzpicture}[scale=0.8]
\begin{axis}[
  x filter/.code= {
    \ifnum\pgfmathresult=1
      \def\pgfmathresult{}
    \fi
 }]
  % This seems working fine
  \addplot[scatter, only marks] table[x=xx, y=yy, col sep=comma]{tmp.txt}; 

  % This cause compilation error, which is
  % |16 error| Missing = inserted for \ifnum. Y ...s] coordinates{(0,0) (1,1) (1,1.5) (2,2)};

  %\addplot[scatter, only marks] coordinates{(0,0) (1,1) (1,1.5) (2,2)};
\end{axis} 
\end{tikzpicture}

\end{document}

答案1

這是因為座標是透過內部浮點表示來處理的,這對我來說是克林貢語1.1Y0.e1(或類似的東西),所以你可以Y在錯誤訊息中看到這一點。解決方案是將其轉換為常規十進制。

也僅適用於整數,但 pgfmath即使對於整數也\ifnum往往會吐出,因此最好進行維度比較以消除複雜性。1.01

\documentclass{article}
\usepackage{pgfplots}   

\pgfplotstableread{
xx yy
0 0
1 1
1 1.5
2 2
}\mytable
\begin{document}

\begin{tikzpicture}[scale=0.8]
\begin{axis}
\addplot[scatter, only marks,  x filter/.code= {
    \ifnum\pgfmathresult=1
      \def\pgfmathresult{}
    \fi
 }] table[x=xx, y=yy]{\mytable}; 

  \addplot+[no marks,  x filter/.code={
\pgfkeys{/pgf/fpu,/pgf/number format/.cd,fixed,verbatim}
\pgfmathprintnumberto{\pgfmathresult}{\mytempvar}
    \ifdim\mytempvar pt=1pt%
      \def\pgfmathresult{}
    \fi
}] coordinates{(0,0) (1,1) (1,1.5) (2,2)};
\end{axis} 
\end{tikzpicture}
\end{document}

在此輸入影像描述

相關內容