[Tex/LaTex] Fill the area under minimum of two functions using tikz and pgfplots

pgfplotspgfplotstabletikz-pgf

I am loading two curves from a file and plot them with \addplot tableĀ [...] {the table.txt}; I have managed to fill the area under a single curve, but I want the minimum of the two curves filled. What is the preferred way to accomplish this using tikz and pgfplots? The image shows an example of the desired result.

Thanks for any help.

enter image description here

Best Answer

This can be done by the fillbetween library which is shipped with pgfplots version 1.10:

enter image description here

\documentclass{standalone}

\usepackage{pgfplots}

\pgfplotsset{compat=1.9}

% \usetikzlibrary{}
\usepgfplotslibrary{fillbetween}


\begin{document}

\begin{tikzpicture}
    \begin{axis}[axis on top,set layers]
    \addplot[blue,name path=A,domain=0:2.3] {sin(deg(2*x))};    

    \addplot[red,name path=B,domain=0:2.3] {cos(deg(2*x))};

    \pgfonlayer{pre main}
    \fill[blue!20!white,intersection segments={of=A and B,sequence={A0 -- B1 -- A2}}]
        -- (axis cs:2.3,\pgfkeysvalueof{/pgfplots/ymin})
        -- (axis cs:0,\pgfkeysvalueof{/pgfplots/ymin})
        -- cycle
    ;
    \endpgfonlayer
    \end{axis}
\end{tikzpicture}
\end{document}

The idea is to use the new intersection segments path instructions provided by fillbetween. It accepts to labelled paths on input and a sequence of intersection segments. Currently, the "minimum" needs to be provided manually. In your case, you need to use the first (0th) segment of the first (A) curve (A0), then the second (1st) of the second curve (B) which is B1, followed by the third (2rd) segment of the first curve which is A2. The other statements specify the bottom line of the filled region. The layering instructions set layers and \pgfonlayer make sure that the stuff appears behind the labelled input paths.

Note that version 1.10 is very young at the time of this writing - you might need a software upgrade.