# 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'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! – J. M. will be back soon Feb 1 '12 at 21:22

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
• @filo you're welcome and thanks for the Accept. – Mr.Wizard Feb 1 '12 at 21:53

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

Another way is to split up the Piecewise function into pieces and use ConditionalExpression.

getPieces[f_Piecewise] :=
Append[ConditionalExpression @@@ First@ f,
ConditionalExpression[Last@ f, ! Or @@ f[[1, All, 2]]]]


Borrowing an example from Plotting piecewise functions with distinct colors - issue found, we can plot it as follows. (Note ColorData[100] is from V10. Another color scheme may be used of course.)

pw = Piecewise[{
{7.95*^6 + x (0.0307 - 2.1558*^-11 x - 1.1279*^-18 x^2) - 507300. Log[6.371*10^6 + 1. x],
0 <= x <= 7157200},
{8.01*^6 + x (0.0220 - 2.1558*^-11 x - 1.1279*^-18 x^2) - 507300. Log[6.371*10^6 + 1. x],
7157200 <= x <= 14314400},
{8.05*^6 + x (0.0190 - 2.1558*^-11 x - 1.1279*^-18 x^2) - 507300. Log[6.371*10^6 + 1. x],
14314400 <= x <= 21471600},
{8.07*^6 + x (0.0180 - 2.1558*^-11 x - 1.1279*^-18 x^2) - 507300. Log[6.371*10^6 + 1. x],
21471600 <= x <= 28628800},
{8.08*^6 + x (0.0179 - 2.1558*^-11 x - 1.1279*^-18 x^2) - 507300. Log[6.371*10^6 + 1. x],
28628800 <= x <= 35786000}},
0];

Plot[Evaluate[getPieces[pw]], {x, 0, 35786000}, PlotStyle -> ColorData[100]]


Note that for this particular code, one might use ConditionalExpression more directly with

Plot[Evaluate[ConditionalExpression @@@ First@pw], {x, 0, 35786000},
PlotStyle -> ColorData[100]]


since the default is not used over this interval.

One can also apply PiecewiseExpand to pw in cases where the inequalities might need simplifying; PiecewiseExpand might also reorder the pieces. (It does on pw.)

• It might be safer to extract data with InternalFromPiecewise. Something like getPieces[f_Piecewise] := MapThread[ConditionalExpression[#2, #1] &, InternalFromPiecewise[f]] – Chip Hurst Jan 6 '16 at 18:00
• @ChipHurst Thanks. It seems like it correlates the default value to True, so I'd still need to replace it with complement of the other domains. But it is a nice way to get all the conditions & expressions. – Michael E2 Jan 6 '16 at 18:26
• Ah! You're right! – Chip Hurst Jan 6 '16 at 18:34