foreach 循环中的多个 pgfplots addplot 命令

foreach 循环中的多个 pgfplots addplot 命令

我试图在此建立 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}

两者的结果均为:

在此处输入图片描述

相关内容