2
$\begingroup$

Let's consider a simple example. I want to plot a function on [0;2], depending on a condition: if x<1, I want to plot x^2, otherwise x^2-1. I found out how to do it:

 Plot[If[x < 1, x^2, x^2 - 1], {x, 0, 2}]

But in my problem I need to plot the same function (x^2), with 1 color for x<1 and with another color otherwise (say, blue and red). I didn't find how to it. It seems like I cannot include colormap function inside the if condition.

Thanks

$\endgroup$
5
  • 3
    $\begingroup$ Make two plots and combine with Show. $\endgroup$
    – Szabolcs
    Commented Jun 24, 2016 at 20:05
  • $\begingroup$ Unfortunately, that didn't work. When I plot them separately (defining color using PlotStyle), everything works. Once I combine them with Show function, it plots everything with the second color, ignoring the first $\endgroup$ Commented Jun 24, 2016 at 20:16
  • 2
    $\begingroup$ That is simply not possible. Show never changes the colour. Are you using Show[Plot[..., PlotStyle -> Red], Plot[..., PlotStyle -> Blue], PlotRange -> All]? I forgot to say that you might need PlotRange -> All within Show. $\endgroup$
    – Szabolcs
    Commented Jun 24, 2016 at 20:30
  • $\begingroup$ That works, thanks $\endgroup$ Commented Jun 24, 2016 at 21:31
  • $\begingroup$ You can convert your If expression to Piecewise with PiecewiseExpand, and then this question is a direct duplicate of the one now linked above your post. See also: (6826), (8199) $\endgroup$
    – Mr.Wizard
    Commented Jun 24, 2016 at 21:40

2 Answers 2

5
$\begingroup$

There are a number of ways of doing this by combining 2 curves. For example

Plot[{If[x < 1, x^2], If[x > 1, x^2 - 1]}, {x, 0, 2},  PlotStyle -> {Red, Blue}]

I don't know if there is a way where the colour information can be tagged to the values themselves.

$\endgroup$
0
6
$\begingroup$

One possibility :

 Plot[
     If[x < 1, x^2, x^2 - 1],
     {x, 0, 2},
     Mesh -> {{1.001}}, 
     MeshFunctions -> {#1 &},
     MeshShading -> {Blue, Red}
     ]

enter image description here

$\endgroup$

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