pgfplots:如何使用 foreach 迭代绘图样式?

pgfplots:如何使用 foreach 迭代绘图样式?

对于以下内容,变量\mystyle没有按预期工作。

因此,我该如何:

1- 通过制作三个值列表来优化代码\myalph\mystyle\mylabel对其进行迭代,foreach而不是逐个输入组合,

2-然后修复代码以使其\mystyle作为线条样式选项工作?

\documentclass{article}
\usepackage{pgfplots}

\begin{document}

\pgfplotsset{alph/.initial=1}
\newcommand*{\getalph}{\pgfkeysvalueof{/pgfplots/alph}} 

\begin{tikzpicture}[
  declare function = { CFDfixedalph(\time) = \time^(\getalph-1); } ]
\begin{semilogxaxis}
\foreach \myalph/\mylabel/\mystyle in {0.1/{one}/dashed , 0.5/{two}/solid , 0.9/{three}/red}{
    \addplot[alph=\myalph, domain = 1e-6 : 1e6, samples = 100, \mystyle] {CFDfixedalph(x)};
    \addlegendentryexpanded{\mylabel}
}
\end{semilogxaxis}
\end{tikzpicture}

\end{document}

答案1

pgfplots 中的循环存在众所周知的缺陷foreach,这在章节中有很好的解释。8.1 实用命令手册 v1.16。这就是我使用\pgfplotsinvokeforeach和一些\noexpand技巧的原因。请注意,这不是使其工作的唯一方法,而是一种可以轻松扩展到更多循环变量的可能方法。那么我相信你在回答你之前的问题当然,不是真的作弊,因为答案真的很棒,一针见血,解释清楚。只是如果我想解决你的问题,我只需声明CFDfixedalph为两个变量的函数,事实确实如此。然后你不需要任何 pgf 键技巧,只需插入你喜欢的 alpha 值。总之,以下方法有效。

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}


\begin{tikzpicture}[
  declare function = { CFDfixedalph(\time,\alph) = \time^(\alph-1); } ]
\begin{semilogxaxis}
\edef\lstAlphs{0.1,0.5,0.9}
\edef\lstLabels{"one","two","three"}
\edef\lstStyles{"dashed","solid","red"}
\pgfplotsinvokeforeach{0,1,2}{
\pgfmathsetmacro{\myalph}{{\lstAlphs}[#1]} % <- CCB (carefully count braces)
\pgfmathsetmacro{\mystyle}{{\lstStyles}[#1]} 
\pgfmathsetmacro{\mylabel}{{\lstLabels}[#1]} 
 \edef\temp{\noexpand\addplot[domain = 1e-6 : 1e6, samples = 100,\mystyle]
    {CFDfixedalph(x,\myalph)};}
 \temp
 \addlegendentryexpanded{\mylabel}
}
\end{semilogxaxis}
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容