How can I add a zero line to a plot?

I do this using the extra ticks mechanism:

  \begin{axis}
    [
      extra y ticks       = 0,
      extra y tick labels = ,
      extra y tick style  = { grid = major },
      ...

This generates a relatively 'light' line with the standard settings: in my plots the appropriate style is something which is a guide to the eye but not overly heavily. I'd imagine that a similar approach can be used to create coloured lines by correct choice of style.


pgfplots stores the axis limit information in xmin,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

after end axis/.append code={
   \draw[ultra thin] (axis cs:\pgfkeysvalueof{/pgfplots/xmin},0) -- (axis cs:\pgfkeysvalueof{/pgfplots/xmax},0);
    \draw[ultra thin] (axis cs:0,\pgfkeysvalueof{/pgfplots/ymin}) -- (axis cs:0,\pgfkeysvalueof{/pgfplots/ymax});
}

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

\draw ({rel axis cs:0,0}|-{axis cs:0,0}) -- ({rel axis cs:1,0}|-{axis cs:0,0});
\draw ({rel axis cs:0,0}-|{axis cs:0,0}) -- ({rel axis cs:0,1}-|{axis cs:0,0});

to draw the lines.

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot {rand};
\draw[ultra thin] (axis cs:\pgfkeysvalueof{/pgfplots/xmin},0) -- (axis cs:\pgfkeysvalueof{/pgfplots/xmax},0);
\draw[ultra thin] (axis cs:0,\pgfkeysvalueof{/pgfplots/ymin}) -- (axis cs:0,\pgfkeysvalueof{/pgfplots/ymax});
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here


Within the axis just plot a line:

\addplot[color=red] coordinates {(-6,0) (6,0)};

Tags:

Pgfplots