5
$\begingroup$

How to plot a function $f(x)=\frac{3(4+x)}{3(2-x)-16}$ (say $x \in [-15,15]$ ) with the condition that i want to give different color for each of the following cases

(i) when $\frac{x+4}{3x+10}>0$ and $\frac{x^2+8x+12}{3x+10}>0$

(ii) when $\frac{x+4}{3x+10}>0$ and $\frac{x^2+8x+12}{3x+10}<0$

(iii) when $\frac{x+4}{3x+10}<0$ and $\frac{x^2+8x+12}{3x+10}>0$

$\endgroup$
5
$\begingroup$

Admittedly, not very different from the naïve answer already posted, just avoided repeating the function definitions.

f[x_] := (3 (x + 4))/(3 (2 - x) - 16);

g[x_] := (x + 4)/(3 x + 10);

h[x_] := (x^2 + 8 x + 12)/(3 x + 10);

a[x_] := (g[x] > 0 && h[x] > 0);
b[x_] := (g[x] > 0 && h[x] < 0);
c[x_] := (g[x] < 0 && h[x] > 0);

Plot[{f[x] && a[x], f[x] && b[x], f[x] && c[x]}, {x, -15, 15}, 
  PlotRange -> {-3, 3}, PlotStyle -> Thickness[.01], Frame -> True, 
  Axes -> False]

enter image description here

$\endgroup$
5
$\begingroup$

You could use the option ColorFunction with ColorFunctionScaling->False. First your conditions:

cond1[x_] := (x+4)/(3x+10)>0 && (x^2+8x+12)/(3x+10)>0
cond2[x_] := (x+4)/(3x+10)>0 && (x^2+8x+12)/(3x+10)<0
cond3[x_] := (x+4)/(3x+10)<0 && (x^2+8x+12)/(3x+10)>0

And your function:

f[x_] := (3(4+x))/(3(2-x)-16)

Then:

Plot[f[x], {x, -15, 15},
    PlotRange -> {All, {-3, 3}},
    ColorFunctionScaling -> False,
    ColorFunction -> Function @ Piecewise[
        {
        {ColorData[97][1], cond1[#]},
        {ColorData[97][2], cond2[#]},
        {ColorData[97][3], cond3[#]}
        },
        ColorData[97][4]
    ]
]

enter image description here

$\endgroup$
5
$\begingroup$

An alternative way to specify a color function:

cf = ColorData[97] @
     (1 + {1, 2}.UnitStep[{(# + 4)/(3 # + 10), (#^2 + 8 # + 12)/(3 # + 10)}]) &;

f[x_] := (3 (4 + x))/(3 (2 - x) - 16)
Plot[f[x], {x, -15, 15}, 
  PlotRange -> {All, {-3, 3}}, 
  BaseStyle -> AbsoluteThickness[5], 
  ColorFunction -> cf, 
  ColorFunctionScaling -> False]

enter image description here

$\endgroup$
2
  • $\begingroup$ Congratulation in the 200k! Well eine. $\endgroup$ – user21 Jun 22 '19 at 3:47
  • $\begingroup$ Thank you @user21. $\endgroup$ – kglr Jun 22 '19 at 3:58
1
$\begingroup$

Naïve solution:

f1[x_] /; And[(x + 4)/(3 x + 10) > 0, (x^2 + 8 x + 12)/(3 x + 10) > 0] := (3 (4 + x))/(3 (2 - x) - 16)
f2[x_] /; And[(x + 4)/(3 x + 10) > 0, (x^2 + 8 x + 12)/(3 x + 10) < 0] := (3 (4 + x))/(3 (2 - x) - 16)
f3[x_] /; And[(x + 4)/(3 x + 10) < 0, (x^2 + 8 x + 12)/(3 x + 10) > 0] := (3 (4 + x))/(3 (2 - x) - 16)

Plot[{f1[x], f2[x], f3[x]}, {x, -15, 15}, PlotRange -> {All, {-10, 10}}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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