30
$\begingroup$

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.

$\endgroup$
0

5 Answers 5

29
$\begingroup$

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
]

final plot

(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.)

$\endgroup$
2
  • $\begingroup$ Ack, you've done what I was going to do! +1, of course! $\endgroup$ Feb 1, 2012 at 21:22
  • $\begingroup$ smooth L1. $0.5x^2$, if $\mid x\mid<1$; otherwise $\mid x\mid -0.5$. f = Piecewise[{{0.5 #^2, Abs[#] < 1}, {Abs[#] - 0.5, Abs[#] >= 1}, {Log[#], 2 < #}}] &; works fine with two colors. $\endgroup$
    – Nick Dong
    Oct 24, 2021 at 2:17
19
$\begingroup$

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]

Mathematica graphics

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

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

Mathematica graphics


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}
]

Mathematica graphics

$\endgroup$
4
  • 4
    $\begingroup$ 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. $\endgroup$
    – David
    Feb 1, 2012 at 20:03
  • $\begingroup$ @David, thanks, that works well. $\endgroup$
    – Mr.Wizard
    Feb 1, 2012 at 20:44
  • $\begingroup$ @filo you're welcome and thanks for the Accept. $\endgroup$
    – Mr.Wizard
    Feb 1, 2012 at 21:53
  • $\begingroup$ smooth L1. $0.5x^2$, if $\mid x\mid<1$; otherwise $\mid x\mid -0.5$. f = Piecewise[{{0.5 #^2, Abs[#] < 1}, {Abs[#] - 0.5, Abs[#] >= 1}, {Log[#], 2 < #}}] &; works fine with two colors. $\endgroup$
    – Nick Dong
    Oct 24, 2021 at 2:21
17
$\begingroup$

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]

Mathematica graphics

$\endgroup$
2
  • $\begingroup$ 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. $\endgroup$
    – Mr.Wizard
    Feb 2, 2012 at 4:38
  • $\begingroup$ smooth L1. $0.5x^2$, if $\mid x\mid<1$; otherwise $\mid x\mid -0.5$ will be treated as three pieces and be plotted with three colors. $\endgroup$
    – Nick Dong
    Oct 24, 2021 at 2:16
1
$\begingroup$

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]]

Mathematica graphics

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.)

$\endgroup$
3
  • 1
    $\begingroup$ It might be safer to extract data with Internal`FromPiecewise. Something like getPieces[f_Piecewise] := MapThread[ConditionalExpression[#2, #1] &, Internal`FromPiecewise[f]] $\endgroup$
    – Greg Hurst
    Jan 6, 2016 at 18:00
  • $\begingroup$ @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. $\endgroup$
    – Michael E2
    Jan 6, 2016 at 18:26
  • $\begingroup$ Ah! You're right! $\endgroup$
    – Greg Hurst
    Jan 6, 2016 at 18:34
0
$\begingroup$

Another possibility:

pw = Piecewise[{{x^2, x < 0}, {x, 2 > x > 0}, {Log[x], x > 2}}];
pw = pw // PiecewiseExpand // Simplify;(* normalization *)
conds = First[pw][[All, 2]]; k = Length[conds]; (* get conditions *)
Plot[pw, {x, -2, 4}, 
 ColorFunction -> 
  Function[x, 
   Evaluate[
    Piecewise[Transpose[{ColorData[1] /@ Range[k], conds}], 
     ColorData[1][k + 1]]]], ColorFunctionScaling -> False, 
 PlotStyle -> AbsoluteThickness[3], Axes -> None, Frame -> True]

plot of piecewise function, with different colors

Changing the coloring scheme should be straightforward.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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