Filling using colors rendered corresponding to the difference between two curves

Suppose there are two curves f1[x] and f2[x], and we want to fill the area between them using colors corresponding to the vaule of f2[x]-f1[x], so that any filling line segemts with the same length will be rendered with same color. My question is, how can we do this using built-in commands like Filling, FillingStyle and ColorFunction, etc? A direct call of ColorFunction will not help because in specification

ColorFunction -> Function[{x, y}, g[x,y]]


the x and y are refered always as the absoulate coordinates, however we need to refer to y2-y1 in our case. I have not figured out how to get this done using pure function.

I can write a code doing this from sketch similiar to the idea suggested in this question, but such treatment is not universal... Besides, there is already such an example documented in Mathematica,

ListLinePlot[Accumulate[RandomReal[{-1, 1}, 250]], ColorFunction -> "Rainbow", Filling -> Axis]


which is actually a similar case to my question but with f1[x] always equal to zero. So I think there should be a solution using only built-in commands...

Furthermore, if there is indeed such a solution, then we can simply generalize the relation from merely f2[x]-f1[x] to more interesting forms.

-
Is it for data-type like ListPlot or analytic like Plot functions ? –  Vitaliy Kaurov Sep 5 '13 at 6:32
@ Vitaliy Kaurov, I am thinking about Plot like functions. ListPlot case can be done easily by manually drawing the line segments and use Show to combine the plots. –  saturasl Sep 5 '13 at 6:39

You can simply use f2[x] - f1[x] in ColorFunction

f1[x_] := Sin[x];
f2[x_] := Cos[x];
Plot[{f1[x], f2[x]}, {x, 0, 2 Pi},
ColorFunction -> Function[{x, y}, ColorData[{"Rainbow", {-1.5, 1.5}}][f2[x] - f1[x]]],
Filling -> {2 -> {1}}, ColorFunctionScaling -> False]


Here -1.5 and 1.5 are minimim and maximum values of difference, ColorFunctionScaling -> False prevent scaling of difference.

Update:

For ListPlot you can use Interpolation in ColorFunction with the same InterpolationOrder

u1 = Accumulate[RandomReal[{-1, 1}, 50]];
u2 = Accumulate[RandomReal[{-1, 1}, 50]];
io = 1;

ListLinePlot[{u1, u2},
ColorFunction -> Function[{x, y}, ColorData[{"Rainbow", {-5, 5}}][
Interpolation[u2, InterpolationOrder -> io][x] -
Interpolation[u1, InterpolationOrder -> io][x]]],
Filling -> {2 -> {1}}, ColorFunctionScaling -> False, InterpolationOrder -> io]


-
Good perspective! However the line segments with same length are not rendered with same color yet. –  saturasl Sep 5 '13 at 7:02
@saturasl There are positive and negative differences. In my example they have different color. Abs[f1[x]-f2[x]] will show absolute difference. –  ybeltukov Sep 5 '13 at 7:11
I see, very nice answer, thanks! –  saturasl Sep 5 '13 at 7:13