# How to plot data with different colors (or symbols) depending on a condition [duplicate]

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

• Make two plots and combine with Show. – Szabolcs Jun 24 '16 at 20:05
• 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 – Mikhail Genkin Jun 24 '16 at 20:16
• 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. – Szabolcs Jun 24 '16 at 20:30
• That works, thanks – Mikhail Genkin Jun 24 '16 at 21:31
• 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) – Mr.Wizard Jun 24 '16 at 21:40

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.

One possibility :

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