# How to set the colour of a contour with a function

In my ContourPlot of E[x_,y_] = Cos[x]+Cos[y], I want the line of any given contour to vary in colour as the angle in the plane varies. The way it should change should be as a function of the angle e.g. $colour(\phi) = a\cos[\phi] + b\sin[\phi]$ for some a and b, which preferably can depend on the value of E.

What is the simple way to do this?

• E is a built-in symbol - don't use it for user defined functions. – corey979 Apr 6 '17 at 12:23

First we define the color function:

color[{x_, y_}] := Hue[(Pi + Arg[x + y I])/(2 Pi)]


Next, the idea is to generate the contour plot and post-process it by adding the VertexColor option to all the lines generated.

cp = Normal@ContourPlot[Cos[x] + Cos[y], {x, -3, 3}, {y, -3, 3}, ContourShading -> None];
cp /. Line[coords_] :> Line[coords, VertexColors -> (color /@ coords)]


Note that the color function can use the value of your function E (although, as others have pointed out, not with this particular function name) by evaluating E[x,y] inside color.

I will rename your function as f, since E is protected in Mathematica. Sadly, I am not aware of a simple way to do what I think you want. But may be this approach helps you for a limited range or gives you some ideas. The contour plot

f[x_, y_] := Cos[x] + Cos[y];
plot1 = ContourPlot[f[x, y], {x, -3, 3}, {y, -3, 3}, ContourStyle -> {Blue}]


is difficult to treat for arbitrary contour. But for simple contours, e.g., for $f = 1/2$, you can solve a angle dependent polar transformation, interpolate the data and plot the curve with varying colors according to the polar angle phi as follows

(*Generate points on specified countrour*)
v = r*{Cos[phi], Sin[phi]};
phis = Range[0, 2 Pi, 2 Pi/100];
data = Table[{phis[[i]], r} /.
First@NSolve[(f @@ v /. phi -> phis[[i]]) == 1/2 && 0 < r <= 3,
r], {i, Length@phis}];
(*Interpolate*)
rphi = Interpolation[data];
(*Plot with contour*)
plot2 = ParametricPlot[v /. r -> rphi[phi], {phi, 0, 2 Pi},
ColorFunction -> Function[{x, y, u}, Hue[u]]];
Show[plot1, plot2]


May be that helps you for a start. Good luck!