PGFplot 中的交叉点

PGFplot 中的交叉点

我可以在 TikZ 中让交叉点工作,但不能在 PGF 图中工作。我定义了一个命令来显示交叉点,以确保它在两种情况下都是相同的。注释掉\ShowIntersection第二张图中的线会导致语法错误。有没有其他方法来命名 PGF 图中的曲线?

\documentclass{standalone}

\usepackage{pgfplots}
\usetikzlibrary{intersections}

\begin{document}

% Define this as a command to ensure that it is same in both cases
\newcommand*{\ShowIntersection}{
\fill 
    [name intersections={of=GraphCurve and HorizontalLine, name=i, total=\t}] 
    [red, opacity=1, every node/.style={above left, black, opacity=1}] 
    \foreach \s in {1,...,\t}{(i-\s) circle (2pt)
        node [above left] {\s}};
}

\begin{tikzpicture}
\draw[name path=GraphCurve, mark=none, domain=-2.5:2.5, thick]%
    plot ({\x},{\x*\x});%

\draw [red, thick, name path=HorizontalLine] 
    (-2.5,3) -- (2.5,3);%

\ShowIntersection% Works fine here
\end{tikzpicture}


\begin{tikzpicture}
\begin{axis}

\addplot[name path=GraphCurve, mark=none, domain=-2.5:2.5, thick]%
    ({x},{x*x});%

\addplot [red, thick, name path=HorizontalLine] 
    coordinates{(-2.5,3) (2.5,3)};%

%\ShowIntersection% Error: Do not know path "GraphCurve" 

\end{axis} 
\end{tikzpicture}
\end{document}

答案1

每个图都在其自己的范围内绘制,因此命名路径在命令之外不会被知道\addplot。在这种情况下,您应该使用选项name path global而不是name path

\documentclass{standalone}

\usepackage{pgfplots}
\usetikzlibrary{intersections}

\begin{document}

\newcommand*{\ShowIntersection}{
\fill 
    [name intersections={of=GraphCurve and HorizontalLine, name=i, total=\t}] 
    [red, opacity=1, every node/.style={above left, black, opacity=1}] 
    \foreach \s in {1,...,\t}{(i-\s) circle (2pt)
        node [above left] {\s}};
}


\begin{tikzpicture}
\begin{axis}

\addplot[name path global=GraphCurve, mark=none, domain=-2.5:2.5, thick]%
    ({x},{x*x});%

\addplot [red, thick, name path global=HorizontalLine] 
    coordinates{(-2.5,3) (2.5,3)};%

\ShowIntersection% Works

\end{axis} 
\end{tikzpicture}
\end{document}

pgfplots 中的图的交集

请注意,name path global如果文档中存在同名的路径(即使它们位于不同的tikzpicture环境中),则会产生问题,一些交集会多次出现。我建议为路径分配唯一的名称,并调整宏\ShowIntersection以将路径名称作为参数:

\documentclass{standalone}

\usepackage{pgfplots}
\usetikzlibrary{intersections}

\begin{document}

% Define this as a command to ensure that it is same in both cases
\newcommand*{\ShowIntersection}[2]{
\fill 
    [name intersections={of=#1 and #2, name=i, total=\t}] 
    [red, opacity=1, every node/.style={above left, black, opacity=1}] 
    \foreach \s in {1,...,\t}{(i-\s) circle (2pt)
        node [above left] {\s}};
}


\begin{tikzpicture}
\begin{axis}

\addplot[name path global=a, mark=none, domain=-2.5:2.5, thick]%
    ({x},{x*x});%

\addplot [red, thick, name path global=b] 
    coordinates{(-2.5,3) (2.5,3)};%

\ShowIntersection{a}{b}

\end{axis} 
\end{tikzpicture}


\begin{tikzpicture}
\draw[name path=c, mark=none, domain=-2.5:2.5, thick]%
    plot ({\x},{\x*\x});%

\draw [red, thick, name path=d] 
    (-2.5,3) -- (2.5,3);%

\ShowIntersection{c}{d}
\end{tikzpicture}
\end{document}

相关内容