
pgfplot を初めて使用して、水平バーのようなグラフを作成してみます。図を参照してください。
やり方はわかっていますが、コードがかなり冗長でデータ量が多いため、繰り返し部分を というマクロにまとめました\labeledRange{beginpos}{endpos}{label}
。また、垂直位置を手動で指定する必要がないようにカウンタ ( vertposition
) を使用しました (範囲ごとに増分させたいため)。ただし、以下のコードでコマンドで使用すると、カウンタが期待どおりに動作しません\node
。上の図では、ラベルLABEL1
とLABEL 2
それぞれ青いバーと赤いバーの近くにあるはずです。
これを動作させるにはどうすればよいですか?
(そして、もう一つの小さな問題として、「ピン」ラインをどうやって取り除くことができるでしょうか?)
\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
環境内の\node
、\draw
などのTikZコマンドはすぐには実行されず、すべてのプロットが完了した後に収集されて実行されます。これは、\path
axis
axis cs:
座標系などを機能させるために必要です (後のプロットで軸の範囲が変更される可能性があるため、すべてのプロットが指定されるまで座標系は固定されません)。このため、すべてのラベルでカウンターの最後の同じ値が使用されます。
別のコマンドを使用する代わりに、の前に( なし)\node
を挿入することができます。node ...
\
;
\addplot
を挿入することができます。 こうすることで、ノードはプロットの最後に自動的に配置されます。
細い線は の使用によって生じますpin
。 の代わりに を使用できます。label
これは のように機能しますが、接続線はありません。または、この場合はとの使用を完全に避けて を直接使用する方がpin
はるかに良いでしょう。pin
label
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}