3

There are some question regarding how to plot an area under a curve with pgfplots. But as far as I can see, all the answers have in common that a function has to be plotted twice with different style options. Example, Pgfplots: how to fill the area under a curve with oblique lines (hatching) as a pattern?

That's also the way I do it currently. Here is an easy working example to play with:

\begin{tikzpicture}[/pgf/declare function={f=1-exp(-x*x);}]
  \begin{axis}[axis x line=center]
    \addplot [domain=-2:2, samples=500, red, fill] {f} \closedcycle;
    \addplot [domain=-5:5, samples=500] {f};
  \end{axis}
\end{tikzpicture}

But especially if one has many plots with non-trivial functions (needing a lot of samples to look smooth!) this can lead to long compile times.

Just setting down the samples for the area filling plot often is not enough, because then some of the area will "overhang" on the wrong side of the curve due to the rough sampling of the plot.

Is it possible to achieve the same output with just plotting the function once to significantly reduce the compile time?

Foo Bar
  • 13,247

1 Answers1

8

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 in a "compile-time-optimized way".

enter image description here

\documentclass{standalone}
\usepackage{pgfplots}

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

\begin{document}

\begin{tikzpicture}[/pgf/declare function={f=1-exp(-x*x);}]
  \begin{axis}[axis x line=center]
    \addplot [name path=f,domain=-5:5, samples=500] {f};

    \path[name path=axis] (axis cs:\pgfkeysvalueof{/pgfplots/xmin},0) -- (axis cs:\pgfkeysvalueof{/pgfplots/xmax},0);

    \addplot[gray!50] fill between[of=f and axis];
  \end{axis}
\end{tikzpicture}
\end{document}

The solution relies on \usepgfplotslibrary{fillbetween}: it assigns name path=f to the function of interest. This is compile-time-optimized: it will use the low-level soft-path of this function. Then, it defines a \path (which is neither drawn nor filled) which resembles the x axis (and receives name path=axis. Finally, \addplot fill between fills the area under f and axis, relying only on compile-time-optimized representations. In fact, this fill operation simply connects f and axis (and computes the resulting bounding box). Consequently, it is supposed to be fast. And: it has more-or-less the same effect as \closedcycle (except that it fills between xmin and xmax which might be larger than the input data range).