26

How to accomplish fill between two curves in pgfplots? For example, I have

...
\addplot coordinates {(0,1) (1,1)};
\addplot file {something.dat};
...

and I would like to have filling between those curves.

29
+50

You can use the \pgfplotstablevertcat command to add the coordinates to your data and then just use the fill option when plotting:

\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\begin{tikzpicture}

% Load the data
\pgfplotstableread{data.dat}\data

% Input the coordinates for the fill boundary, sort them from highest to lowest x value
\pgfplotstablesort[sort cmp={float >}]\coordinates{
0 0
1 1
}

% Concatenate the two series
\pgfplotstablevertcat{\filledcurve}{\data}
\pgfplotstablevertcat{\filledcurve}{\coordinates}


\begin{axis}
% Plot the concatenated tables
\addplot[fill=gray!40,draw=none] table {\filledcurve};

% Plot the data and the coordinates for reference
\addplot[blue,mark=*,line width=2pt] table {\data};
\addplot[orange,mark=*,line width=2pt] table {\coordinates};
\end{axis}
\end{tikzpicture}

\end{document}

My datafile "data.dat" looks like this

0 2
0.5 -1
1 3

Yielding the following output:

Filling the area between two curves using pgfplots

21

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

\documentclass{standalone}
\usepackage{pgfplots}

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

\begin{tikzpicture}

\begin{axis}
\addplot[name path=A,blue,mark=*,line width=2pt] table {
0 2
0.5 -1
1 3
};
\addplot[name path=B,orange,mark=*,line width=2pt] coordinates  {(0,0) (1,1)};

\addplot[gray!40] fill between[of=A and B];

\end{axis}
\end{tikzpicture}

\end{document}

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 gray!40. Note that the fill between segment will automatically be drawn on a separate layer, i.e. it is behind the main paths. Note that fill between is independent of the sampling density, the input type, and even the plot handler of the two input paths.

  • 2
    This simpler solution deserves a upvote. – qweruiop Dec 11 '16 at 18:49

Your Answer

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