Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.)

share|improve this question
    
Nearly duplicates: (9684), (18964) –  Mr.Wizard Oct 18 at 18:19

4 Answers 4

up vote 7 down vote accepted

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[]}]

enter image description here

share|improve this answer
    
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? –  bobthechemist Apr 18 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 Apr 18 at 14:32
    
I agree, it doesn't matter, I just found it curious. –  bobthechemist Apr 18 at 14:36
    
@bobthechemist There is no line becasue it is only a rectangle and I'm not plottign y=1 at all. –  Kuba Apr 18 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}}]]

enter image description here

share|improve this answer

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}}]

enter image description here

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

enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.