tikz 中 addplot 和 draw 的扩展有什么不同吗?

tikz 中 addplot 和 draw 的扩展有什么不同吗?

有人能帮我理解为什么在两次调用 mydraw 时,addplot 执行了两次,但 draw 只执行了一次?我看到了两个 addplot 创建的“点”,但只看到了第二次 draw 的标签。请注意,注释掉第二个 \mydraw 会导致第一个绘制正确。

\documentclass{minimal}

\usepackage{pgfplots}
\usepackage{pgfkeys}
\usepackage{tikz}

\newcommand{\setValue}[1]{\pgfkeys{/variables/#1}}
\newcommand{\getValue}[1]{\pgfkeysvalueof{/variables/#1}}
\newcommand{\declare}[1]{%
 \pgfkeys{
  /variables/#1.is family,
  /variables/#1.unknown/.style = {\pgfkeyscurrentpath/\pgfkeyscurrentname/.initial = ##1}
 }%
}

\declare{}

\newcommand{\mydraw}[1]{%

  \declare{test/}
  \setValue{test, value = #1}

  \addplot [mark=*] coordinates{(\getValue{test/value},0.3)};
  \draw node at (axis cs:\getValue{test/value},0.4) [below] {\getValue{test/value}}; 
}


\begin{document}

\begin{tikzpicture}
  \begin{axis}

    \addplot coordinates{(0,0) (1,1)};

    \mydraw{0.4}
    \mydraw{0.6}
    \end{axis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

答案1

这是因为pgfplots有一个调查阶段和一个实际执行阶段。因此,您的命令会被执行,但不会真正执行,因此您会覆盖该值。您可以使用 pgfplots 手册 v1.16 第 543 页上的技巧来修复此问题。

\documentclass[tikz,border=3mm]{standalone}

\usepackage{pgfplots}

\newcommand{\setValue}[1]{\pgfkeys{/variables/#1}}
\newcommand{\getValue}[1]{\pgfkeysvalueof{/variables/#1}}
\newcommand{\declare}[1]{%
 \pgfkeys{
  /variables/#1.is family,
  /variables/#1.unknown/.style = {\pgfkeyscurrentpath/\pgfkeyscurrentname/.initial = ##1}
 }%
}

\declare{}

\newcommand{\mydraw}[1]{%
  \declare{test/}
  \setValue{test, value = #1}
  \edef\temp{
  \noexpand\addplot [mark=*] coordinates{(\getValue{test/value},0.3)};
  \noexpand\draw node at (axis cs:\getValue{test/value},0.4) [below] {\getValue{test/value}}; 
  }
  \temp
}


\begin{document}

\begin{tikzpicture}
  \begin{axis}

    \addplot coordinates{(0,0) (1,1)};

    \mydraw{0.4}
    \mydraw{0.6}
    \end{axis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

答案2

问题不是\draw,问题是\SetValue必须运行两次。

\documentclass{standalone}
\usepackage{pgfplots}

\newcommand{\setValue}[1]{\pgfkeys{/variables/#1}}
\newcommand{\getValue}[1]{\pgfkeysvalueof{/variables/#1}}
\newcommand{\declare}[1]{%
 \pgfkeys{
  /variables/#1.is family,
  /variables/#1.unknown/.style = {\pgfkeyscurrentpath/\pgfkeyscurrentname/.initial = ##1}
 }%
}

\declare{}

\newcommand{\mydraw}[1]{%

  \declare{test/}
  \setValue{test, value = #1}
  \pgfplotsextra{\setValue{test, value = #1}}

  \addplot [mark=*] coordinates{(\getValue{test/value},0.3)};
  \draw node at (axis cs:\getValue{test/value},0.4) [below] {\getValue{test/value}}; 
}


\begin{document}

\begin{tikzpicture}
  \begin{axis}

    \addplot coordinates{(0,0) (1,1)};

    \mydraw{0.4}
    \mydraw{0.6}
    \end{axis}
\end{tikzpicture}

\end{document}

相关内容