計數器在 pgfplot 中未如預期運作

計數器在 pgfplot 中未如預期運作

使用 pgfplot (第一次),我嘗試建立一個帶有水平條的圖表。見圖。

在此輸入影像描述

我知道如何做到這一點,但由於程式碼非常冗長並且我有大量數據,因此我在名為 的巨集中提取了重複部分\labeledRange{beginpos}{endpos}{label}。我還使用了計數器 ( vertposition) 來擺脫手動指定垂直位置(因為我希望它為每個範圍遞增)。但是,當\node在下面的程式碼中的命令中使用時,計數器的行為並不像我預期的那樣。在上圖中,標籤LABEL1LABEL 2 應分別位於藍色和紅色條附近。

我怎樣才能讓它發揮作用?

(還有一個小問題,我要怎麼擺脫「pin」線?)

\documentclass{article}
\usepackage{pgfplots}     
\begin{document}

%\labeledRange{start}{end}{label}
\newcounter{vertposition}
\newcommand{\labeledRange}[3]{
  \addplot coordinates {(#1,\arabic{vertposition}) (#2,\arabic{vertposition})};
  \node[coordinate, pin=right:{#3}] 
          at (axis cs:#2,\arabic{vertposition}) {};
  \stepcounter{vertposition}
  }

\begin{figure}[ht]
  \centering
  \begin{tikzpicture}
    \begin{axis}[xmin=0,xmax=100] %,ytick=\empty]

      %using my macro -> label position is wrong
      \labeledRange{10}{20}{LABEL 1}
      \labeledRange{60}{70}{LABEL 2}

      %without macro -> works fine
      \addplot coordinates {(20,3) (50,3)};
      \node[coordinate, pin=right:{LABEL 3}] 
          at (axis cs:50,3) {};

    \end{axis}

  \end{tikzpicture}
\end{figure}

\end{document}

答案1

TikZ 指令如\node\draw\pathaxis環境中不會立即執行,而是收集並在所有繪圖完成後執行。這對於使axis cs:坐標係等工作正常工作是必要的(因為以後的繪圖仍然可以改變軸範圍,在指定所有繪圖之前,坐標係不會固定)。因此,所有標籤都使用相同的計數器最後值。

您可以在命令之前\node插入node ...(不帶\) ,而不是使用單獨的命令。這樣,該節點將自動放置在繪圖的末端。;\addplot

細線是由於您使用pin.您可以改為使用label,其工作方式類似於pin但沒有連接線。或者,在這種情況下,最好完全避免使用pinand label,直接使用 the node

\documentclass{article}
\usepackage{pgfplots}     
\begin{document}

%\labeledRange{start}{end}{label}
\newcounter{vertposition}
\newcommand{\labeledRange}[3]{
  \addplot coordinates {(#1,\arabic{vertposition}) (#2,\arabic{vertposition})} node [black,anchor=west] {#3};
  \stepcounter{vertposition}
  }

\begin{figure}[ht]
  \centering
  \begin{tikzpicture}
    \begin{axis}[xmin=0,xmax=100] %,ytick=\empty]

      %using my macro
      \labeledRange{10}{20}{LABEL 1}
      \labeledRange{60}{70}{LABEL 2}

      %without macro
      \addplot coordinates {(20,3) (50,3)};
      \node[coordinate, label=right:{LABEL 3}] 
          at (axis cs:50,3) {};

    \end{axis}

  \end{tikzpicture}
\end{figure}

\end{document}

相關內容