# Force ColorFunction to take same parameters as the function it colours

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


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


• Read under Details in the ColorFunction documentationâ€”first argument is x, second is y when using Plot. Use the second. Commented Mar 5, 2019 at 13:55
• 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}
– Tom
Commented Mar 5, 2019 at 13:57
• 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]. Commented Mar 5, 2019 at 13:57
• No it still doesn't work. I'll update and you'll see.
– Tom
Commented Mar 5, 2019 at 13:58
• Yes, you're right, the argument to the colour function is scaled to go from 0 to 1 unless you specify ColorFunctionScaling -> False Commented Mar 5, 2019 at 14:01

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


Clear[f]