如何在pgfplots中基于字符串列过滤表格(兼容LuaLaTeX)
在pgfplots中实现字符串比较过滤表格
尝试在pgfplots中通过字符串比较过滤表格数据时编译失败,使用LuaLaTeX编译器,原代码及错误信息如下:
原代码
\documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis}[grid=major] \addplot+ [ unbounded coords=discard, x filter/.expression={\thisrow{type}=="foo" ? x : nan}, ] table[trim cells=true] { x y type 1 2 "foo" 1.5 2.5 "bar" 2 3 "foo" 2.5 3.5 "bar" 3 4 "foo" }; \end{axis} \end{tikzpicture} \end{document}
编译错误
! Package PGF Math Error: Could not parse input '@@str@@:foo' as a floating point number, sorry. The unreadable part was near '@@str@@:foo'. (in "\"foo\"==\"foo\" ? x : nan').
数字对比可行示例
若改用数字比较则可正常运行,代码如下:
\documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis}[grid=major] \addplot+ [ unbounded coords=discard, x filter/.expression={\thisrow{type}==42 ? x : nan}, ] table[trim cells=true] { x y type 1 2 42 1.5 2.5 5 2 3 42 2.5 3.5 42 3 4 12 }; \end{axis} \end{tikzpicture} \end{document}
解决方案
pgfplots的x filter/.expression仅支持数值运算,无法直接处理字符串比较,可通过以下两种方式解决:
方法1:使用表格filter expr选项(推荐)
利用pgfmath内置的strcmp函数进行字符串比较(相等返回0,不等返回1),代码调整如下:
\documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis}[grid=major] \addplot+ [unbounded coords=discard] table[trim cells=true, filter expr={strcmp(\thisrow{type}, "foo") == 0}] { x y type 1 2 foo 1.5 2.5 bar 2 3 foo 2.5 3.5 bar 3 4 foo }; \end{axis} \end{tikzpicture} \end{document}
- 注意:表格中的字符串无需加引号;若必须保留引号,需将比较目标改为
"\"foo\""。
方法2:使用x filter/.code自定义逻辑
通过TeX命令读取当前行的字符串值并手动判断:
\documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis}[grid=major] \addplot+ [ unbounded coords=discard, x filter/.code={ % 获取当前行type列的值 \pgfplotstablegetelem{\pgfplotstablerow}{type}\of\pgfplotstablecurrenttable % 字符串匹配则保留x值,否则设为nan \ifx\pgfplotsretval foo \else \def\pgfmathresult{nan} \fi }, ] table[trim cells=true] { x y type 1 2 foo 1.5 2.5 bar 2 3 foo 2.5 3.5 bar 3 4 foo }; \end{axis} \end{tikzpicture} \end{document}
内容的提问来源于stack exchange,提问作者mistral
相关产品推荐
相关产品推荐

