# Plot Filling restricted to domain segment

I'm trying to plot the function $f(x)=\dfrac{1}{x^2}$, filling the square area from (0,0) to (1,1) with purple and filling the area under the curve from 1 to 4 with red.

However, Mathematica is not showing the purple filling, and the red part is not completely filled down to the x-axis.

My current code:

Show[Plot[1/(x^2), {x, 0, 4}, PlotStyle -> Blue, AspectRatio -> 1],
Plot[{1/(x^2), 1}, {x, 0, 1}, PlotStyle -> Blue, Filling -> {1 -> {{2}, {Purple, None}}}],
Plot[1/(x^2), {x, 1, 4}, PlotStyle -> Blue, Filling -> Axis, FillingStyle -> Red]]


What Mathematica gives me:

What's wrong with my code?

(I'm also very new to Mathematica, so any suggestions on a more elegant way to fill the curve would be appreciated.)

• Nearly duplicates: (9684), (18964) Commented Oct 18, 2014 at 18:19

One Plot can do too:

Plot[{If[x < 1, 1/(x^2)], If[x > 1, 1/(x^2)]}, {x, 0, 4}
, AspectRatio -> 1
, Filling -> {2 -> {Axis, Red}}
, Epilog -> {Purple, Rectangle[]}
]


• Is it just the image sampling or is your answer the only one that doesn't have the horizontal blue line above the purple shading? Commented Apr 18, 2014 at 14:29
• @bobthechemist Yes there isn't any line. Well, it fits the description, not the image sample but I believe it doesn't matter.
– Kuba
Commented Apr 18, 2014 at 14:32
• I agree, it doesn't matter, I just found it curious. Commented Apr 18, 2014 at 14:36
• @bobthechemist There is no line becasue it is only a rectangle and I'm not plottign y=1 at all.
– Kuba
Commented Apr 18, 2014 at 14:37
Show[Plot[1/(x^2), {x, 0, 4}, PlotStyle -> Blue, AspectRatio -> 1],
Plot[1, {x, 0, 1}, FillingStyle -> Purple, Filling -> Bottom,
PlotStyle -> Blue],
Plot[1/(x^2), {x, 1, 4}, PlotStyle -> Blue, Filling -> Axis,
FillingStyle -> Red, PlotRange -> {Full, {0, 1}}]]


Another variation, using ConditionalExpression:

Plot[{
ConditionalExpression[x^-2, x <= 1],
ConditionalExpression[x^-2, x > 1],
ConditionalExpression[1, x <= 1]}
, {x, 0, 4}, PlotStyle -> Blue,
Filling -> {2 -> {Axis, Red}, 3 -> {Axis, Purple}}]


Plot[{x^-2, UnitStep[1 - x], Boole[x > 1] x^-2}, {x, 0, 4}, PlotStyle -> Blue,
Filling -> {3 -> {{2}, {Purple, Red}}}]