我试图在此建立 Christian Feuersänger 的回答:https://tex.stackexchange.com/a/17817/193625
\addplot
我希望循环主体中不止有 on,还有多个。然而这会导致错误:Use of \pgffor@scanround doesn't match its definition.
有人可以帮忙吗?
梅威瑟:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\foreach \x/\l in {-2/a, -1/b, 1/c, 2/d}{
\edef\temp{\noexpand
\addplot%
coordinates{ (\x, 0.5) (\x, 1) }
node [above] {\l};
% comment the next three lines to make it work
\addplot%
coordinates{ (\x, -0.5) (\x, -1) }
node [below] {\l};
}
\temp
}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
您需要\noexpand
在每个\addplot
宏之前放置:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\foreach \x/\l in {-2/a, -1/b, 1/c, 2/d}{
\edef\temp{
\noexpand\addplot%
coordinates{ (\x, 0.5) (\x, 1) }
node [above] {\l};
\noexpand\addplot%
coordinates{ (\x, -0.5) (\x, -1) }
node [below] {\l};
}
\temp
}
\end{axis}
\end{tikzpicture}
\end{document}
您还可以嵌套\foreach
循环(这可能会进一步简化事情,具体取决于您的具体设置):
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\foreach \x/\l in {-2/a, -1/b, 1/c, 2/d}{
\foreach \p/\ya/\yb in {above/0.5/1, below/-0.5/-1}{
\edef\temp{
\noexpand\addplot%
coordinates{ (\x, \ya) (\x, \yb) }
node [\p] {\l};
}\temp
}
}
\end{axis}
\end{tikzpicture}
\end{document}
两者的结果均为: