# Showing the area between two curves using rectangles (Riemann Sum)

I've been looking for a solution to draw the area between two curves using infinitesimal rectangles, like the image below:

It would be great also to use only one rectangle to show the difference between heights:

Has anyone ever done something similar that I may use as a starting point?

• @JPi ok, that's good. Do you want to contribute to the answer? Oct 11, 2015 at 15:45
• Starting point: Research through tex.stackexchange.com/search?q=riemann Oct 11, 2015 at 15:49
• Can be done with GeoGebra and exporting to TikZ as well
– user31729
Oct 11, 2015 at 15:59

Here's one option using pgfplots:

The code:

\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}

\pgfmathdeclarefunction{curvei}{1}{%
\pgfmathparse{0.05*#1*(#1-7)*(#1-12)}%
}
\pgfmathdeclarefunction{curveii}{1}{%
\pgfmathparse{-0.03*(#1)*(#1-6)*(#1-18)}%
}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
xmin=-0.5,
xmax=8,
ymin=-5,
ymax=7,
domain=0.5:7.5,
xtick={0.75,6.25},
xticklabels={$a$,$b$},
ytick={0},
axis on top
]

{curvei(x)};
{curveii(x)};

{curvei(x)};
{curveii(x)};

{curvei(x)};
{curveii(x)};
\end{axis}
\end{tikzpicture}

\end{document}


And the second one:

The code:

\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\usetikzlibrary{decorations.pathreplacing}
\pgfplotsset{compat=1.12}

\pgfmathdeclarefunction{curvei}{1}{%
\pgfmathparse{0.05*#1*(#1-7)*(#1-12)}%
}
\pgfmathdeclarefunction{curveii}{1}{%
\pgfmathparse{-0.03*(#1)*(#1-6)*(#1-18)}%
}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
xmin=-0.5,
xmax=8,
ymin=-5.5,
ymax=7,
domain=0.5:7.5,
xtick={0.75,6.25},
xticklabels={$a$,$b$},
ytick={0},
]

{curvei(x)};
{curveii(x)};
fill between[of=curveA and curveB,soft clip={domain=0.75:6.25}];

coordinates {(3,-7) (3,7)};
\path[name intersections={of=curveA and line,by={top}}];
\path[name intersections={of=curveB and line,by={bottom}}];

\filldraw[gray!100!cyan,opacity=0.5]
([xshift=-10pt]top) rectangle ([xshift=10pt]bottom);
\draw[decorate,decoration=brace]
([xshift=12pt]top) -- node[right=4pt] {$y_{T} - y_{B}$} ([xshift=12pt]bottom);
\draw[decorate,decoration={brace,raise=3pt}]
([xshift=10pt]bottom) -- node[below=4pt] {$\Delta x$} ([xshift=-10pt]bottom);
\node[above,red!70!black] at (1.5,4.8) {$y_{T}$};
\node[above,cyan] at (1.5,-4.8) {$y_{B}$};
\end{axis}
\end{tikzpicture}

\end{document}

• @bru1987 You're welcome. I updated my answer with some improvements that night be of interest for you. Oct 11, 2015 at 20:00
• thank you Gonzalo, I'm always impressed by your great LaTeX skills, specially when working on Tikz and pgfplots. Have a great day, Best Regards. Oct 12, 2015 at 10:39