Is it possible to have both the axis on top and the grid on the very bottom (or somewhere in between some other planes/lines/...) of a plot?

Example figure with axis on top=true but the grid on top is ugly:

Example figure with axis on top=false and the grid looks nice behind the yellow plane, but axes and arrows look bad behind the drawing.

Here is a tiny code example

\documentclass{article} \usepackage{pgfplots}
\begin{document} \begin{tikzpicture}
\begin{axis}[grid=major,axis x line=bottom,axis y line=left] %axis on top
\end{axis}
\end{tikzpicture} \end{document}


Can anyone put the axis to the top without having the grid on top?

-

We can make use of the after end axis/.code key here to redraw the axis lines after everything else is done. The macro for drawing the axes (and grid lines, tick marks and tick labels) is the internal macro pgfplots@draw@axis, so we need to make it available by assigning a new name without @ first. Then we can define a new style that initially sets the axis lines, tick marks and tick labels to transparent, and uses the after end axis/.code to reset the opaqueness, hide the grid and call pgfplots@draw@axis.

This looks a bit intimidating at first, but once the style axis lines on top is defined, all you have to do in the axis itself is use the style.

\documentclass{article}
\usepackage{pgfplots}
\begin{document}

\makeatletter \newcommand{\pgfplotsdrawaxis}{\pgfplots@draw@axis} \makeatother

\pgfplotsset{axis line on top/.style={
axis line style=transparent,
ticklabel style=transparent,
tick style=transparent,
axis on top=false,
after end axis/.append code={
\pgfplotsset{axis line style=opaque,
ticklabel style=opaque,
tick style=opaque,
grid=none}
\pgfplotsdrawaxis}
}
}

\begin{tikzpicture}
\begin{axis}[grid=major,axis x line=bottom,axis y line=left,axis line on top]
\end{axis}
\end{tikzpicture}

\end{document}


-
nice. I think I have to go a few layers deeper to unleash the full power of pgf/tikz :) –  kromuchi Mar 29 '11 at 12:04
@Jake I know this here is quite old - but so is the need to improve layered graphics in pgfplots. I would appreciate if I could discuss some of the involved issues with you as you appear to be very experienced in tikz / TeX / pgfplots. If so, I would be glad to receive an E-Mail (for example ludewich on users sourceforge net) –  Christian Feuersänger Aug 22 '11 at 19:10

Well, you could plot it twice, first with the grid, and again without it, but with axis on top.

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[grid=major,enlargelimits=false]
\end{axis}
\begin{axis}[axis on top=true,enlargelimits=false]

I hope there is an other way as this requires plotting twice, but as far as I could tell there doesn't seem to be an easy way to separate the axis from the grid, but I could easily be wrong as I'm new to pgfplots.