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?

  • 2
    $\begingroup$ E is a built-in symbol - don't use it for user defined functions. $\endgroup$ – 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)]

Mathematica graphics

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

enter image description here

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

enter image description here

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


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.