10
$\begingroup$

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

$\endgroup$
10
$\begingroup$

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

$\endgroup$
  • $\begingroup$ 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? $\endgroup$ – bobthechemist Apr 18 '14 at 14:29
  • $\begingroup$ @bobthechemist Yes there isn't any line. Well, it fits the description, not the image sample but I believe it doesn't matter. $\endgroup$ – Kuba Apr 18 '14 at 14:32
  • $\begingroup$ I agree, it doesn't matter, I just found it curious. $\endgroup$ – bobthechemist Apr 18 '14 at 14:36
  • $\begingroup$ @bobthechemist There is no line becasue it is only a rectangle and I'm not plottign y=1 at all. $\endgroup$ – Kuba Apr 18 '14 at 14:37
9
$\begingroup$
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

$\endgroup$
8
$\begingroup$

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

$\endgroup$
4
$\begingroup$
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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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