1
$\begingroup$

I am trying to adapt [this solution for colouring the different sections of a Piecewise function]

I want to colour based on the x-axis value. I have two functions I want to do this for, one is Piecewise the other can be written as Piecewise.

MWE

a[x_]:= x^2;
b[x_] = Log[x];
f = Piecewise[{{a[x], 0<= x<= 3}, {b[x], 3<x <= 7}}]

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

colorFunction = f
piecewiseParts = Length@colorFunction[[1, 1]]
colors =  {Red, Green}
colorFunction[[1, 1, All, 1]] = colors

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

The linked example uses a Piecewise function defined like g (use g everywhere instead of g) - I need to use something that is formed like f.

$\endgroup$

1 Answer 1

1
$\begingroup$

You can treat f like a pure function, but keep the definitions and dependencies of a and b:

a[x_] := x^2;
b[x_] := Log[x];
f = Piecewise[{{a[x], 0 <= # <= 3}, {b[x], 3 < # <= 7}}, 0] &;
colorFunction = f;
colors = {Red, Green};
colorFunction[[1, 1, All, 1]] = colors;
Plot[f[x], {x, -2, 4}, ColorFunction -> colorFunction, 
 ColorFunctionScaling -> False]

Returns:

enter image description here

$\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.