[Tex/LaTex] Put grid below plot in pgfplots

pgfplotstikz-pgf

In a plot with pgfplots I would like to draw, from background to foreground, in the following order:

  1. (background) grid;
  2. (intermediate layer) plot;
  3. (foreground) axis.

As specified in this answer,

Adding axis on top to the axis options means axis lines, ticks and
grids are printed on top of the stuff inside the environment.

So, this is not the correct option for this. This code

\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{shapes.geometric,arrows,arrows.meta}
\pgfplotsset{
    /pgfplots/layers/Bowpark/.define layer set={
        axis background,axis grid,main,axis ticks,axis lines,axis tick labels,
        axis descriptions,axis foreground
    }{/pgfplots/layers/standard},
}

\begin{document}

\begin{tikzpicture}
\begin{axis}[/pgfplots/layers/Bowpark,
             width=\textwidth,
             xmin=-0.5, xmax=6,
             ymin=-0.5, ymax=4,
             axis line style = thin,
             axis lines=middle,
             axis line style={-{Stealth[length=2.5mm]}},
             thick,
             grid=major, grid style={dashed,gray!30}]

    \addplot[blue, samples = 100] {x^2};

\end{axis}
\end{tikzpicture}

\end{document}

doesn't work neither (plot is above grid, but also above the axis). I used \addplot[blue, samples = 100] {x^2}; instead of \addplot[samples = 100] {x^(1/2)}; to better highlight the superposition of the plot, the grid and the axis.

enter image description here

enter image description here

What's wrong? Note that also trying

\pgfplotsset{
    /pgfplots/layers/Bowpark/.define layer set={
        axis background,main,axis grid,axis ticks,axis lines,axis tick labels,
        axis descriptions,axis foreground
    }{/pgfplots/layers/standard},
}

(switched the order of main and axis grid) produces the same output.

Maybe something in my configuration ignores the layers order?

Best Answer

This is discussed at length in section 4.27 of the pgfplots manual. All I did is to define a new layer set based on axis on top in which I flip the order of axis grid and main.

\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{shapes.geometric,arrows,arrows.meta}
\pgfplotsset{
    /pgfplots/layers/Bowpark/.define layer set={
        axis background,axis grid,main,axis ticks,axis lines,axis tick labels,
        axis descriptions,axis foreground
    }{/pgfplots/layers/standard},
}

\begin{document}

\begin{tikzpicture}
\begin{axis}[width=\textwidth,
             xmin=-0.5, xmax=6,
             ymin=-0.5, ymax=4,
             axis line style = thin,
             axis lines=middle,
             axis line style={-{Stealth[length=2.5mm]}},
             thick,
             grid=major, grid style={dashed,gray!30},
             set layers=Bowpark]

    \addplot[blue, samples = 100] {x^2};

\end{axis}
\end{tikzpicture}

\end{document}

enter image description here

EDIT: Fixed bug, I was too sloppy, sorry!