Tikz-PGF – How to Color a Region Produced by TikZ

tikz-pgf

I'm using xelatex and I want to color the region enclosed by y=f(x), y=g(x) and the lines x=a and x=b in the code below (just like the picture below). How can I do that?

\documentclass{article}
\usepackage{tikz} 
\usetikzlibrary{arrows}
\begin{document}

\begin{tikzpicture}
\draw [->,>=triangle 45] (-2,0) -- (5,0) node [right] {$x$};
\draw [->,>=triangle 45] (0,-2.2) -- (0,3.2) node [above] {$y$};
\draw[very thick] (-1.5,.5) to [out=300,in=180] (-.5,-.5)
to [out=0,in=180] (3,2.5)
to [out=360,in=140] (4.5,2) ;
\draw[very thick] (-1.5,-1.5) to [out=350,in=240] (4.5,1) ;
\draw[very thick] (4.2,0)--(4.2,2.2);
\node at (4.2,0) [below] {$b$};
\draw[very thick] (-1,0)--(-1,-1.55);
\node at (-1,0) [above] {$a$};
\node at (1.5,2.2) [above] {$y=f(x)$};
\node at (2,-1.5) [right] {$y=g(x)$};
\end{tikzpicture}

\end{document}

enter image description here

Best Answer

enter image description here

\documentclass{article}
\usepackage{tikz} 
\usetikzlibrary{arrows}
\begin{document}

\begin{tikzpicture}
\begin{scope}
\clip(-1,-5)rectangle(4.2,5);
\clip (-1.5,.5) to [out=300,in=180] (-.5,-.5)
to [out=0,in=180] (3,2.5)
to [out=360,in=140] (4.5,2) --++(0,-5)--(-1,-5)--cycle;
\fill[red] (-1.5,-1.5) to [out=350,in=240] (4.5,1)--++(0,5)--(-1,5)--cycle;
\end{scope}
\draw [->,>=triangle 45] (-2,0) -- (5,0) node [right] {$x$};
\draw [->,>=triangle 45] (0,-2.2) -- (0,3.2) node [above] {$y$};
\draw[very thick] (-1.5,.5) to [out=300,in=180] (-.5,-.5)
to [out=0,in=180] (3,2.5)
to [out=360,in=140] (4.5,2) ;
\draw[very thick] (-1.5,-1.5) to [out=350,in=240] (4.5,1) ;
\draw[very thick] (4.2,0)--(4.2,2.2);
\node at (4.2,0) [below] {$b$};
\draw[very thick] (-1,0)--(-1,-1.55);
\node at (-1,0) [above] {$a$};
\node at (1.5,2.2) [above] {$y=f(x)$};
\node at (2,-1.5) [right] {$y=g(x)$};
\end{tikzpicture}

\end{document}

You can make the code even better by using named coordinates and reuse of paths.

I still haven't figured out an automatic way to determine the extremal values of the curves, so the path appendices

--++(0,-5)--(-1,-5)--cycle

and

--++(0,5)--(-1,5)--cycle

can be replaced by automatically correct values.