13

I want to fill the area between two curves and have the grid lines below the filling. Is this possible?

(From Showing grid on top of plot fill with PGFplots? I thought axis on bottom might work, but this seems not to be a command.)

Edit: The filling method is the one suggested in Fill the area between two curves calculated by pgfplots by Christian Feuersanger, and requires a recent version of pgfplots.

\documentclass{standalone}
\usepackage{tikz,pgfplots}

\pgfplotsset{compat=1.10}
\usepgfplotslibrary{fillbetween}

\begin{document}

\begin{tikzpicture}
\begin{axis}[axis lines = middle,
    smooth,
    no markers,
    xlabel = {$x$},
    ylabel = {$y$},
    minor tick num =1,
    grid=both,
    domain=0:2,]
        \addplot+[domain=0:1,samples=200,name path=A,black] {sqrt(x)};
        \addplot+[domain=0:1,name path=B,black] {x};
        \addplot[blue!50] fill between[of=A and B];
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

15

If you add set layers option the axis environment, it sets a hierarchricrhchaheal(!?) order as the standard layer order, namely axis background, axis grid, axis ticks, axis lines, axis tick labels, main, axis descriptions, axis foreground. This simply switches the order of drawing order. Hence it is feature not a bug. Otherwise you can reorder the layers as a customized layer style

\documentclass{standalone}
\usepackage{tikz,pgfplots}

\pgfplotsset{compat=1.10}
\usepgfplotslibrary{fillbetween}

\begin{document}

\begin{tikzpicture}
\begin{axis}[set layers,
    axis lines = middle,
    smooth,
    no markers,
    xlabel = {$x$},
    ylabel = {$y$},
    minor tick num =1,
    grid=both,
    domain=0:2,]
        \addplot+[domain=0:1,samples=200,name path=A,black] {sqrt(x)};
        \addplot+[domain=0:1,name path=B,black] {x};
        \addplot[blue!50] fill between[of=A and B];
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

4

percusse's answer is correct.

What beats me is that pgfplots should have done that automatically as soon as it encounters a fill between plot.

Consequently, there is a second answer:


This is a bug and will be fixed in the next version of pgfplots (probably 1.11 once it is ready).

  • Using this a bit more: percusse's answer puts the filling on top of gridlines and on top of tick labels (1, 2, 3, etc). I think ideally the filling should go above grid lines but under tick labels. I am not sure how uniform that opinion is, though. – Chris Chudzicki Apr 13 '14 at 23:52
  • @mrc I see. Pgfplots comes with two presets, the one shown by percusse and axis on top which puts both grid and tick labels on top. Perhaps your is better, I do not know. – Christian Feuersänger Apr 14 '14 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.