# I want an image like the following image. (Question about Plot)

Let $$n$$ be a positive integer which is greater than or equal to $$2$$.
Let $$f$$ be a function from $$[1,n]$$ to $$\mathbb{R}$$.
Let $$g$$ be a function from $$[1,n]$$ to $$\mathbb{R}$$ such that $$g(x)=f(k)$$ if $$x\in[k,k+1)$$ for some $$k\in\{1,2,\dots,n\}$$.
Let $$S:=\{x\in [1,n]\mid f(x)\leq g(x)\}.$$
Let $$T:=\{x\in [1,n]\mid g(x)< f(x)\}.$$
Let $$B:=\{(x,y)\in\mathbb{R}^2\mid x\in S, f(x)\leq y\leq g(x)\}.$$
Let $$R:=\{(x,y)\in\mathbb{R}^2\mid x\in T, g(x)\leq y\leq f(x)\}.$$
I want to paint the area $$B$$ blue.
I want to paint the area $$R$$ red.

I copied the following code:

n = 10;
f[x_] := Sin[x];
rectangles[f_, a_, b_, n_] := {
Opacity[0.0],
Blue,
EdgeForm[Black],
N@Table[Rectangle[{a + k (b - a)/n, 0}, {a + (k + 1) (b - a)/n, f[a + k (b - a)/n]}], {k, 0, n - 1}]
};
Plot[f[x], {x, 1, n}, Epilog -> rectangles[f, 1, n, n-1],
AxesOrigin -> {1, 0}, ImageSize -> Large, Frame -> True]


I want an image like the following image:

Thank you very much.

• This should be achievable by describing the areas covered by rectangles as a function and using the Filling option between the two functions. Aug 14, 2022 at 3:57
• @kirma Thank you very much for your answer. Aug 14, 2022 at 3:58

A quick hack:

n = 10;
f[x_] := Sin[x];
rectangles[f_, a_, b_, n_] := {Opacity[0.0], Blue, EdgeForm[Black],
N@Table[Rectangle[{a + k (b - a)/n, 0}, {a + (k + 1) (b - a)/n,
f[a + k (b - a)/n]}], {k, 0, n - 1}]};
Plot[{f[x], f[Floor[x]]}, {x, 1, n},
PlotStyle -> {Automatic, None}, Filling -> {1 -> {{2}, {Blue, Red}}},
Epilog -> rectangles[f, 1, n, n - 1], AxesOrigin -> {1, 0},
ImageSize -> Large, Frame -> True]


The stepped function is achieved just by Floor, two-sided filling between the normal and stepped function is achieved with Filling option and just for completeness, plot style for the stepped function is set to None.

• kirma, Thank you very very much for your excellent answer. Aug 14, 2022 at 4:14