[Tex/LaTex] tikz/pgfplots advanced z-order axis/grid

pgfplotstikz-pgf

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
    \addplot+[mark=none,fill=yellow,draw=red] {0.1*x^2} \closedcycle;
    \end{axis}
\end{tikzpicture} \end{document} 

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

Best Answer

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]
    \addplot+[mark=none,fill=yellow,draw=red] {0.1*x^2} \closedcycle;
    \end{axis}
\end{tikzpicture}

\end{document} 

axis with grid behind, axis lines on top