[Tex/LaTex] pgfplots: How to make axes go through the origin

pgfplots

For pgfplots, in all the 2D examples I've seen so far, and in the manual, the location of axes seems to be specified in terms of location within the plot box, i.e., relative to top, bottom. How does one specify that x- and y-axes intersect at the origin? And how do they go through some other user-specified coordinate pairs?

Best Answer

As Joseph said, to get the axis lines to pass through the origin, you can use the axis lines=middle option:

\begin{axis}[
    axis lines=middle
]
\addplot {x^2+rand};
\end{axis}

To choose an arbitrary point for the axis lines to pass through, a pragmatic approach might be to transform the data points and the labels using the x filter/.code and xticklabel keys, which can be wrapped in a custom style like axis lines origin={<x>,<y>}. The problem with this approach is that the tick labels can end up quite weird depending on the origin you choose.

\pgfplotsset{
    axis line origin/.style args={#1,#2}{
        x filter/.append code={ % Check for empty or filtered out numbers
                \ifx\pgfmathresult\empty\else\pgfmathparse{\pgfmathresult-#1}\fi
            },
        y filter/.append code={
                \ifx\pgfmathresult\empty\else\pgfmathparse{\pgfmathresult-#2}\fi
            },
        xticklabel=\pgfmathparse{\tick+#1}\pgfmathprintnumber{\pgfmathresult},
        yticklabel=\pgfmathparse{\tick+#2}\pgfmathprintnumber{\pgfmathresult}
    }
}
...

\begin{axis}[
    axis lines=middle,
    axis line origin={1,2}
]
\addplot +[domain=-2:2] {x^2+rand};
\end{axis}