3
$\begingroup$

ColorFunction doesn't behave as I expect. It doesn't seem to take the same value as the function itself. See below. I plot the function Sin[x]^2 and use it to specify the opacity of the curve. Hence I would expect the tops of the curves to be visible, and to fade away to invisible at the bottom. Instead I get the following behaviour. Any explanation?

Plot[Sin[x]^2, {x, 0, 4 Pi}, ColorFunction -> Function[x, Opacity[Sin[x]^2, Blue]]]
Plot[Sin[x]^2, {x, 0, 8 Pi}, ColorFunction -> Function[x, Opacity[Sin[x]^2, Blue]]]

enter image description here

I think the problem is something to do with rescaling. If I plot in the range {x, 0, 1} then it works as expected.

Plot[Sin[20 x]^2, {x, 0, 1}, ColorFunction -> Function[x, Opacity[Sin[20 x]^2, Blue]]]

enter image description here

$\endgroup$
6
  • 1
    $\begingroup$ Read under Details in the ColorFunction documentation—first argument is x, second is y when using Plot. Use the second. $\endgroup$
    – Szabolcs
    Commented Mar 5, 2019 at 13:55
  • $\begingroup$ I read it. I don't understand. I want x to be the argument. But it seems to be rescaling the range of x to be in {0,1} $\endgroup$
    – Tom
    Commented Mar 5, 2019 at 13:57
  • $\begingroup$ f=Sin[x]; Function[x, Opacity[f, Blue]] does not work because x does not appear literally in the function. It must be inlined in some way: Function[x, Opacity[Sin[x], Blue]]. It's better to define f as a proper function that is called as f[x]. $\endgroup$
    – Szabolcs
    Commented Mar 5, 2019 at 13:57
  • $\begingroup$ No it still doesn't work. I'll update and you'll see. $\endgroup$
    – Tom
    Commented Mar 5, 2019 at 13:58
  • 2
    $\begingroup$ Yes, you're right, the argument to the colour function is scaled to go from 0 to 1 unless you specify ColorFunctionScaling -> False $\endgroup$
    – Szabolcs
    Commented Mar 5, 2019 at 14:01

1 Answer 1

5
$\begingroup$

The best way to do this is to use the second argument of the colour function. The meaning of each argument for each function is documented under Details in ColorFunction.

Clear[f]
f = Sin[x]^2;
Plot[f, {x, 0, 4 Pi}, 
 ColorFunction -> Function[{x, y}, Opacity[y, Blue]]]

To fix your example,

Clear[f]
f[x_] := Sin[x]^2
Plot[f[x], {x, 0, 4 Pi}, 
 ColorFunction -> Function[{x, y}, Opacity[f[x], Blue]], 
 ColorFunctionScaling -> False]
$\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.