pgfplot addplot 帶有預先定義的座標

pgfplot addplot 帶有預先定義的座標

我有一堆預先定義的座標,我想透過重複使用座標在圖中繪製多條線。如果我更改座標值,我只想更改一次,而不是在多個座標列表中更改。因此我想做類似下面的事情

\documentclass[tikz]{standalone}

\usepackage{tikz,pgfplots}
\pgfplotsset{compat=1.9}

\begin{document}
\begin{tikzpicture}

\begin{axis}
\coordinate (p1) at (1,1);
\coordinate (p2) at (2,2);
\addplot coordinates{(p1)(p2)};
\end{axis}

\end{tikzpicture}
\end{document}

生成看起來像這樣的東西

但顯然生活不可能那麼容易,因為我收到以下錯誤

Runaway argument?
p1)(p2)\pgfplots@EOI \pgfplotsscanlinelengthcleanup 
\pgfplots@coord@stream@end 
\ETC.
Paragraph ended before \pgfplots@loop@next was complete.
<to be read again> 
               \par 
l.15 

我也嘗試過在軸環境之外定義座標,但這也不起作用。

關於如何在 \addplot 座標列表中使用預定義座標有什麼想法嗎?

答案1

正如我所提到的,這可能是因為 pgfplots 延遲了它的擴展。這樣就可以自動放大相關區域等等。因此我無法為您提供一個很好的解決方案。我能夠產生的最好的解決方法是

\documentclass[tikz]{standalone}
\makeatletter
% from https://tex.stackexchange.com/q/56353/121799
\newcommand{\gettikzxy}[3]{%
  \tikz@scan@one@point\pgfutil@firstofone#1\relax
  \global\edef#2{\the\pgf@x}%
  \global\edef#3{\the\pgf@y}%
}
\newcommand{\gettikzcoordinates}[2]{%
  \tikz@scan@one@point\pgfutil@firstofone#1\relax
  \pgfmathsetmacro{\myx}{round(0.99626*\the\pgf@x/0.0283465)/1000}
  \pgfmathsetmacro{\myy}{round(0.99626*\the\pgf@y/0.0283465)/1000}
  \global\edef#2{(\myx,\myy)}%
}
\makeatother
\usepackage{tikz,pgfplots}
\pgfplotsset{compat=1.9}

\begin{document}
\begin{tikzpicture}
\coordinate (p1) at (1,1);
\coordinate (p2) at (2,2);
\begin{axis}
\gettikzcoordinates{(p1)}{\Pone}
\gettikzcoordinates{(p2)}{\Ptwo}
\addplot coordinates{\Pone\Ptwo};
\end{axis}
\end{tikzpicture}
\end{document}

該程式碼產生所需的圖。正如您可以檢查的那樣,如果您移動語句\begin{axis}之前的\coordinate內容,您將收到錯誤,主要是因為在需要座標時未定義座標。很多時候你可以透過使用來逃脫\edef\temp{<something>}\temp,但在這種情況下我只會陷入無限循環。 (\gettikzxy這裡不相關,我只是想指出我從哪裡得到如何提取座標的想法。)

相關內容