此 MWE
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[scale=0.75]
\begin{axis}[ylabel=Y-Axis, xlabel=X-Axis
, xmin=2, xmax=10, ymin=0, ymax=12, clip=false, axis y line*=right]
\foreach \blah in {0.9,0.5,0.2,0.1,0.05,0.02,0.01,0.005}{
\addplot[mark=none, domain=2:10, thick] {-ln(\blah/x^2)/ln(x)} node [pos=0,left] {$c_2=$}; %Varying c_2 values
}
\end{axis}
\end{tikzpicture}
\end{document}
产生此结果
请注意,c_2=
等号左侧的节点没有值。我想我可以通过以下方法解决这个问题:
\addplot[mark=none, domain=2:10, thick] {-ln(\blah/x^2)/ln(x)} node [pos=0,left] {$c_2=$\blah}; %Varying c_2 values
但这不起作用,因为 PDFLaTeX 告诉我,在引用时有一个“未定义的控制序列” \blah
。
我怎样才能让它工作?
答案1
PGFPlots 包含一个特殊的循环机制,可以避免未扩展宏的问题:
\pgfplotsinvokeforeach{<list>}{
< code where the list element is available as #1 >
}
在你的情况下,你可以写
\pgfplotsinvokeforeach {0.9,0.5,0.2,0.1,0.05,0.02,0.01,0.005}{
\addplot[mark=none, domain=2:10, thick] {-ln(#1/x^2)/ln(x)} node [pos=0,left] {$c_2=#1$};
}
要得到
答案2
您可以\blah
在超出范围之前强制进行扩展:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\def\doit#1{%
\addplot[mark=none, domain=2:10, thick] {-ln(#1/x^2)/ln(x)} node [pos=0,left] {$c_2=#1$}; %Varying c_2 values
}
\begin{tikzpicture}[scale=0.75]
\begin{axis}[ylabel=Y-Axis, xlabel=X-Axis
, xmin=2, xmax=10, ymin=0, ymax=12, clip=false, axis y line*=right]
\foreach \blah in {0.9,0.5,0.2,0.1,0.05,0.02,0.01,0.005}{
\expandafter\doit\expandafter{\blah}
}
\end{axis}
\end{tikzpicture}
\end{document}
答案3
我想知道为什么在这种情况下不使用直接扩展。我们看到了语法以及需要保护的内容。
\begin{tikzpicture}[scale=0.75]
\begin{axis}[ylabel=Y-Axis,xlabel=X-Axis,xmin=2,
xmax=10,ymin=0,ymax=12,clip=false,axis y line*=right]
\foreach\x in {0.9,0.5,0.2,0.1,0.05,0.02,0.01,0.005}{%
\edef\x{\noexpand\addplot[mark=none,domain=2:10,thick]
{-ln(\x/x^2)/ln(x)}node[pos=0,left] {$c_2=\x$}}\x;
}
\end{axis}
\end{tikzpicture}
编辑2012/7/19
1.Marc van Dongen 在他的评论中报告的问题在我的计算机上也适用于 Jake 的解决方案:
\begin{document}
\begin{tikzpicture}[scale=0.75]
\begin{axis}[ylabel=Y-Axis,xlabel=X-Axis,xmin=2,xmax=10,ymin=0,
ymax=12, clip=false, axis y line*=right]
\pgfplotsinvokeforeach{0.9,0.5,0.2,0.1,0.05,0.02,0.01,0.005}{%
\addplot[mark=none,domain=2:10,thick]{-ln(#1/x^2)/ln(x)}
node [pos=0,left] {$c_2=#1$};
}%
\end{axis}
\end{tikzpicture}
\end{document}
我可能搞砸了什么。我会让 Jake 确认或反驳这一点,然后再发布一个可行的示例。
2.\x
只要用户知道自己在做什么,在 tikzpicture 环境中(重新)定义是无害的。\x
不是由 TikZ 本身定义的。
这是一个在我的计算机上可以运行的示例:
\begin{document}
% Style 1:
\begin{tikzpicture}
\begin{axis}
\foreach \am in {1,2,3}{%
\addplot{x^\am};
\addlegendentryexpanded{$x^\am$}
}
\end{axis}
\end{tikzpicture}
% Style 2:
\begin{tikzpicture}
\begin{axis}
\foreach \x in {1,2,3}{%
\edef\x{%
\noexpand\addplot{x^\x};
\noexpand\addlegendentry{$x^\x$}
}\x
}
\end{axis}
\end{tikzpicture}
\end{document}