Plotting piecewise function with distinct colors in each section

I have a piecewise function that I would like to plot but I was wondering if it is possible that each part of the function that is plotted when its corresponding condition is true be plotted with a different color from the other parts. That is, if I have a Piecewise function Piecewise[{{val1, cond1},{val2,cond2},{val3,cond3}}] then I want val1, val2, and val3 to be plotted with different colors so that I can differentiate each case in the plot.

-

Here is one method, now more robust:

pwSplit[_[pairs : {{_, _} ..}]] := Piecewise[{#}, Indeterminate] & /@ pairs

pwSplit[_[pairs : {{_, _} ..}, expr_]] :=
Append[pwSplit@{pairs}, pwSplit@{{{expr, Nor @@ pairs[[All, 2]]}}}]


Testing:

pw = Piecewise[{{x^2, x < 0}, {x, 2 > x > 0}, {Log[x], x > 2}}];

Plot[Evaluate[pwSplit@pw], {x, -2, 4}, PlotStyle -> Thick, Axes -> False]


pw = Integrate[Piecewise[{{E^x, x^2 <= 1}}, Sin[x]], x];

Plot[Evaluate[pwSplit @ pw], {x, -2, 2}, PlotStyle -> Thick, PlotRange -> Full]


I like Heike's method so much I have to do my own version of it.

Module[{i = 1},
Plot[pw, {x, -2, 2}, PlotStyle -> Thick]
/. x_Line :> {ColorData[1][i++], x}
]


-
This plots the functions as zero out of their piecewise domain. You can get rid of this behavior by using Piecewise[{#, {Indeterminate, True}}] instead. However, this assumes that the original Piecewise does not use a True directive already. –  David Feb 1 '12 at 20:03
@David, thanks, that works well. –  Mr.Wizard Feb 1 '12 at 20:44
Thanks a lot for your help! –  mirandaio Feb 1 '12 at 21:37
@filo you're welcome and thanks for the Accept. –  Mr.Wizard Feb 1 '12 at 21:53

Here's an alternative approach than Spartacus' answer. What he did is splitting up the piecewise function into many different functions valid in only a small domain; what I am doing here is directly plotting the piecewise function as given, while the coloring is done using ColorFunction.

I'll use the same function as Spartacus,

f = Piecewise[{{#^2, # <= 0}, {#, 0 < # <= 2}, {Log[#], 2 < #}}] &


Step by step to the result

Now let's create a ColorFunction that does the desired thing out of this. I'll do this using Part, i.e. double brackets [[ ]], which is not limited to lists only.

First, create a copy of f.

colorFunction = f;


Now we need to find out how many pieces there are in this function; for this we have to extract those into a list we can allpy Length to. Step by step:

colorFunction[[1]]

Piecewise[{{#1^2, #1 <= 0}, {#1, Inequality[0, Less, #1, LessEqual, 2]}, {Log[#1], 2 < #1}}, 0]


That's the full function body. By applying another [[1]], we can get the first argument of Piecewise:

colorFunction[[1, 1]]

{{#1^2, #1 <= 0}, {#1, 0 < #1 <= 2}, {Log[#1], 2 < #1}}


From this matrix-shaped list, we'd like to get the length, leaving us with

piecewiseParts = Length@colorFunction[[1,1]]


Alright! Now make some colors out of that. The default plot colors are stored in ColorData[1][x], where x=1,2,3,4... is the usual blue/magenta/yellowish/green and so on.

colors = ColorData[1][#] & /@ Range@piecewiseParts

{RGBColor[0.2472, 0.24, 0.6], RGBColor[0.6, 0.24, 0.442893], RGBColor[0.6, 0.547014, 0.24]}


Now we need to take these color directives and inject them into the original function (that is, the colorFunction copy I've made in the beginning), so that it replaces squares and logarithms by reds and blues. This is some more Part acrobatics:

colorFunction[[1, 1, All, 1]] = colors


Done! colorFunction is now identical to the original function f, only that the actual functions have been replaced by colors. It looks like this:

Piecewise[{{RGBColor[...], # <= 0}, {RGBColor[...], 0 < # <= 2}, {RGBColor[...], 2 < #}}] &


Now it's time to plot, see the completed code below.

The completed code

f = Piecewise[{{#^2, # <= 0}, {#, 0 < # <= 2}, {Log[#], 2 < #}}] &;

colorFunction = f;
piecewiseParts = Length@colorFunction[[1, 1]];
colors = ColorData[1][#] & /@ Range@piecewiseParts;
colorFunction[[1, 1, All, 1]] = colors;

Plot[
f[x],
{x, -2, 4},
ColorFunction -> colorFunction,
ColorFunctionScaling -> False
]


(The option ColorFunctionScaling determines whether Mathematica scales the domain for the color function to $[0,1]$. Handy in some cases, not so much here, since our self-made colorFunction is constant in this domain.)

-
Ack, you've done what I was going to do! +1, of course! –  Guess who it is. Feb 1 '12 at 21:22
Thanks a lot for your help! –  mirandaio Feb 1 '12 at 21:37

It looks like Plot is kind enough to split a plot of a Piecewise function in separate Line objects, so you could do something like

pl = Plot[Piecewise[{{x^2, x < 0}, {x, 2 > x > 0}, {Log[x], 3 > x > 0}}],
{x, -2, 4}];
lines = Cases[pl, _Line, Infinity];
Graphics[Transpose[{Array[ColorData[1], Length[lines]], lines}], Axes -> True]


-
Beautiful. I almost checked this possibility but then I thought "Piecewise is supposed to be continuous; it won't work." I am glad somebody bothered to check. –  Mr.Wizard Feb 2 '12 at 4:38