在 pgfplots 直方图中添加垂直线

在 pgfplots 直方图中添加垂直线

如何在直方图中的条形之间添加垂直线?

以下构建了我的图表:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[ybar stacked, symbolic x coords={1,2,3,4,5},
    xtick=data, ymin=0, bar width=30pt]
  \addplot[ybar,fill=lightgray] coordinates {
    (1,3) (2,2) (3,1) (4,5) (5,3) };
\end{axis}
\end{tikzpicture}
\end{document}

此代码的输出

我如何在(例如)第三列和第四列之间放置一条垂直线?

我试过了\draw (3.5,0) -- (3.5,5);,但没用。看起来要找到图中的具体点很复杂(与有关axis cs?),但我没能理解任何示例,也没能在 500 页的手册中找到位置。

答案1

举几个例子:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
If you really have 1,2,... as ticklabels, you can just remove the symbolic coordinates and use axis cs:
\begin{center}
\begin{tikzpicture}
  \begin{axis}[ybar stacked, %symbolic x coords={1,2,3,4,5},
    xtick=data, ymin=0, bar width=30pt]
  \addplot[ybar,fill=lightgray] coordinates {
    (1,3) (2,2) (3,1) (4,5) (5,3) };
\draw (axis cs:3.5,0) -- (axis cs:3.5,5.5);,
\end{axis}
\end{tikzpicture}
\end{center}

Or add compat=11 (or higher) and don't use axis cs:
\begin{center}
\pgfplotsset{compat=1.11} % normally add this to preamble
\begin{tikzpicture}
  \begin{axis}[ybar stacked, %symbolic x coords={1,2,3,4,5},
    xtick=data, ymin=0, bar width=30pt]
  \addplot[ybar,fill=lightgray] coordinates {
    (1,3) (2,2) (3,1) (4,5) (5,3) };
\draw (3.5,0) -- (3.5,5.5);,
\end{axis}
\end{tikzpicture}
\end{center}

If you have non-numeric ticklabels, use xticklabels instead of symbolic coordinates:
\begin{center}
\begin{tikzpicture}
  \begin{axis}[ybar stacked, xticklabels={foo,bar,baz,baa,abc},
    xtick=data, ymin=0, bar width=30pt]
  \addplot[ybar,fill=lightgray] coordinates {
    (1,3) (2,2) (3,1) (4,5) (5,3) };
\draw (axis cs:3.5,0) -- (axis cs:3.5,5.5);,
\end{axis}
\end{tikzpicture}
\end{center}

Instead of manually specifying a y-coordinate you can access the value used in the axis with pgfkeysvalueof:
\begin{center}
\begin{tikzpicture}
  \begin{axis}[ybar stacked, xticklabels={foo,bar,baz,baa,abc},
    xtick=data, ymin=0, bar width=30pt]
  \addplot[ybar,fill=lightgray] coordinates {
    (1,3) (2,2) (3,1) (4,5) (5,3) };
\draw (axis cs:3.5,\pgfkeysvalueof{/pgfplots/ymin}) -- (axis cs:3.5,\pgfkeysvalueof{/pgfplots/ymax});,
\end{axis}
\end{tikzpicture}
\end{center}


\end{document}

相关内容