4

I am on my first adventure in plotting with LaTeX. I managed to get my bar chart plotted. I have two groups of values for which I want to show the average. I intend to put a horizontal bar over the bar chart and let it indicate the average values. Drawing is unfortunately not coupled to scaling or similar. In the moment I have to change something in the scaling/labeling everything will be out of its place. Is there a best practice way of drawing lines (or arrows) that are corresponding to data values of the underlying chart?

1 Answers1

5

I am assuming that you are having trouble using a tikz \draw within a \pgfplot's axis environment. In this case you need to use the axis cs coordinate system as the dotted line in red illustrates:

enter image description here

Notes:

  • To add a label to this line you can use a node as part of the draw.
  • The positioning of the label is covered at Moving a label along the path.
  • Thanks to Jake's answer at Apply shift to (current axis.left of origin), the second MWE below should work without requiring specification of the minimum and maximum x values. Only the y value needs to be specified in the \VerticalPos definition.

Code: Specify both minimum and maximum x values

\documentclass{article}
\usepackage{pgfplots}

\begin{document} \begin{tikzpicture} \begin{axis} \addplot {x*x}; \draw [ultra thick, dotted, draw=red] (axis cs: -6,12) -- (axis cs: 6,12) node[pos=0.5, above] {$y=12$}; \end{axis} \end{tikzpicture} \end{document}


Code: Automatically determine both minimum and maximum x values

\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{calc}

\begin{document} \begin{tikzpicture} \begin{axis} \addplot {x*x};

\newcommand*{\VerticalPos}{12}% Desired vertical postion
\coordinate (Left)  at ($(current axis.left of origin) +(axis direction cs: 0,\VerticalPos)$);
\coordinate (Right) at ($(current axis.right of origin)+(axis direction cs: 0,\VerticalPos)$);

\draw [ultra thick, dotted, draw=red] 
    (Left) -- (Right)
    node[pos=0.5, above] {$y=\VerticalPos$};

\end{axis} \end{tikzpicture} \end{document}

Peter Grill
  • 223,288