I frequently need to draw a horizontal or vertical line passing through the axis origin that spans the entire width or height of my plot area. I don't want to use axis lines=middle
, because the tick labels clutter up the plot area. So far, I've been using something like \addplot [black, no markers] coordinates (-5,0) (5,0);
to draw a horizontal line, but the approach doesn't feel right, and it's not very flexible: If I change my axis range, the line might be too short, and I have to explicitly set xmin
and xmax
because otherwise the line influences the plot limits.
What's the proper way to add a vertical or horizontal line passing through a certain point (typically the axis origin) that spans the entire height/width of a plot?
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=-6,xmax=6
]
\addplot {rand};
\addplot [red, no markers] coordinates {(-7,0) (7,0)};
\end{axis}
\end{tikzpicture}
\end{document}
Best Answer
pgfplots
stores the axis limit information inxmin,ymin,xmax,xmin
keys (Jake reminded that this was not the case in the earlier versions) and we can access those key values via\pgfkeysvalueof{}
command.The advantage of this is that the coordinates snap to the location of the origin and more importantly it does not disturb the bounding box if the origin is not visible in the particular plots. If this has to be done frequently, one can create a style where the additional commands goes into the
This would add these commands to the instruction list when the axis processing is finished.
The disadvantage of this method is that it does not work with logarithmic plots. In that case, you can use
to draw the lines.