TransWikia.com

Add vertical line to a pgfplots histogram

TeX - LaTeX Asked by Martyn Quick on March 15, 2021

How do I add a vertical line between the bars in a histogram?

The following constructs my diagram:

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}

Output of this code

How do I place a vertical line between (for example), the 3rd and 4th column?

I’ve tried draw (3.5,0) -- (3.5,5);, but this doesn’t work. It looks like getting hold of specific points in the diagram is complicated (something to do with axis cs?) but I’ve not managed to make any sense of any examples nor find the place in the 500-page manual.

One Answer

A few examples:

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}

Correct answer by Torbjørn T. on March 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP