1
$\begingroup$

This question already has an answer here:

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$

marked as duplicate by Mr.Wizard plotting Jun 24 '16 at 21:39

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 3
    $\begingroup$ Make two plots and combine with Show. $\endgroup$ – Szabolcs Jun 24 '16 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$ – Mikhail Genkin Jun 24 '16 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 Jun 24 '16 at 20:30
  • $\begingroup$ That works, thanks $\endgroup$ – Mikhail Genkin Jun 24 '16 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 Jun 24 '16 at 21:40
4
$\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$
4
$\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.