Upper approximating rectangles with tikz?

For lower approximating rectangles, using this answer I was able to draw as many rectangles as I want

\documentclass{standalone}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{pgfplots}
\tikzset{
point/.style={circle,draw=black,inner sep=0pt,minimum size=3pt}
}
\pgfplotsset{
soldot/.style={color=blue,only marks,mark=*}
}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
xtick={4},ytick={0},
xticklabel={$1$},
xlabel=$x$,ylabel=$y$,
y=0.3cm, xmax=4.4,ymax=17.8,ymin=-2,xmin=-0.5,
enlargelimits=true,
axis lines=middle,
clip=false,
domain=0:4,
axis on top
]
\addplot [fill=blue!30, ybar interval, samples=52]
{x^2}\closedcycle;
%\addplot[soldot,red]coordinates {(4,16)} node [anchor=west,text=black]  {$(1,1)$};
\addplot[const plot] coordinates {(4,0)(4,16)};
\end{axis}
\end{tikzpicture}
\end{document}


Output(For 50 rectangles):

How can draw the upper approximating rectangles for any number of rectangles(Take 50 rectangles for instance).

• Note: Your blue rectangles are not really below the curve. They are because your curve is strictly increasing. – Paul Gaborit Mar 21 '18 at 7:30

For the parabola function in your case this is pretty easy by just shifting it to the left according to the bar width. Have a look at the comments in the code on how to do this.

\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
% define some parameters which are later used
% for the functions
\pgfmathsetmacro{\DomainMin}{0}
\pgfmathsetmacro{\DomainMax}{4}
\pgfmathtruncatemacro{\Samples}{25}
% calculate the width of the resulting bars
\pgfmathsetmacro{\BarWidth}{(\DomainMax-\DomainMin)/\Samples}
\begin{axis}[
xmin=-0.5,
xmax=4.4,
ymax=17.8,
ymin=-2,
axis lines=middle,
domain=\DomainMin:\DomainMax,
samples=\Samples,
axis on top,
]
% use the calculated bar shift value to shift the function
\addplot [fill=red!30,ybar interval]  {(x+\BarWidth)^2};
\addplot [fill=blue!30,ybar interval] {x^2};

• comment the second \addplot line!? – Stefan Pinnow Mar 21 '18 at 8:38