[Tex/LaTex] Fill the area between two curves calculated by pgfplots


This is essentially the same question as fill the area between two curves when their coordinates are known.

In that question, the curves were defined by known coordinates. I want to fill the area between two curves but I want the curves to be calculated from pgfplots (or gnuplot).

Let's say that the curves are defined by these functions:

f(x) = sqrt(x)

g(x) = sqrt(x/2)

Best Answer

Version 1.10 of pgfplots has been released just recently, and it comes with a new solution for the problem to fill the area between plots.

Note that the old solution is still possible and still valid; this here is merely an update which might simplify the task. In order to keep the knowledge base of this site up-to-date, I present a solution based on the new fillbetween library here:

enter image description here



    \begin{axis}[thick,smooth,no markers]
        \addplot+[name path=A,black] {sqrt(x)};
        \addplot+[name path=B,black] {sqrt(x/2)};

        \addplot[blue!50] fill between[of=A and B];

The solution relies on \usepgfplotslibrary{fillbetween} which activates the syntax \addplot fill between[of=<first> and <second>]. The style for the filled region is given in the option list as usual, it is blue!50. Note that the fill between segment will automatically be drawn on a separate layer, i.e. it is behind the main paths.