我的具体问题涉及 TikZ/pgfplots(参见下面的 MWE),但我认为存在一个更通用的解决方案(或者由于我无法找到的深层原因而不存在)。
我希望预定义一些值,然后在环境的选项中传递它(在我的情况下,是环境的xtick
或/和)。xticklabels
axis
tikzfigure
我读过一些相关的问题(最接近的是将宏传递给 tikz/pgf 中的向量声明但我没能使可接受的解决方案适用于我的情况)。我猜想问题在于 LateX 在读取宏时会扩展宏(如果我错了请纠正我),这意味着它将\begin{someenvironment}[option1=\mymacro]
尝试将字符串传递\mymacro
给option1
(而不关心它是否以反斜杠开头,或者关心得太晚)。
我大致了解\foo\bar
语法是如何修复的\expandafter\foo\bar
,但我无法得到任何类似的技巧,无论我使用多少\begin{axis}[xticklabels=
expandafters 作为前缀 -
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{pgfplots}
\begin{document}
%The figure I want to obtain (but without giving "A1,A2,A3" explicitly)
\begin{tikzpicture}
\begin{axis}[
xmin=0,xmax=10,
ymin=0,ymax=4,
xtick={1,4,7},
xticklabels={A1,A2,A3},
ytick=\empty
]
\addplot+[domain=0:10,samples=100,no markers]{sqrt(x)};
\end{axis}
\end{tikzpicture}
% This fails to do what I want, as the commas are not understood as value separators
\begin{tikzpicture}
\newcommand{\tiklist}{A1,A2,B}
\begin{axis}[
xmin=0,xmax=10,
ymin=0,ymax=4,
xtick={1,4,7},
xticklabels={\tiklist},
ytick=\empty
]
\addplot+[domain=0:10,samples=100,no markers]{sqrt(x)};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
您可以通过.expanded
pgfkeys 的处理程序强制扩展(第 82.4.6 节“扩展和多个值”,第 890 页,pgfmanual,v3.0.1a)。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\newcommand{\tiklist}{A1,A2,B}
\begin{axis}[
xmin=0,xmax=10,
ymin=0,ymax=4,
xtick={1,4,7},
xticklabels/.expanded=\tiklist,
ytick=\empty
]
\addplot+[domain=0:10,samples=100,no markers]{sqrt(x)};
\end{axis}
\end{tikzpicture}
\end{document}
答案2
您可以通过以下方式强制扩展:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{pgfplots}
\begin{document}
%The figure I want to obtain (but without giving "A1,A2,A3" explicitly)
\begin{tikzpicture}
\begin{axis}[
xmin=0,xmax=10,
ymin=0,ymax=4,
xtick={1,4,7},
xticklabels={A1,A2,A3},
ytick=\empty
]
\addplot+[domain=0:10,samples=100,no markers]{sqrt(x)};
\end{axis}
\end{tikzpicture}
% This fails to do what I want, as the commas are not understood as value separators
\begin{tikzpicture}
\newcommand{\tiklist}{A1,A2,B}
\edef\tmp{\noexpand\begin{axis}[
xmin=0,xmax=10,
ymin=0,ymax=4,
xtick={1,4,7},
xticklabels={\tiklist},
ytick=\empty
]}\tmp
\addplot+[domain=0:10,samples=100,no markers]{sqrt(x)};
\end{axis}
\end{tikzpicture}
\end{document}