2

I tried

ContourPlot[f[x, y], {x, -2, 2}, {y, -2, 2}, ContourLabels->automatic] 

, but it messes up the contourplot. How can I just add values to the contours for

ContourPlot[f[x, y], {x, -2, 2}, {y, -2, 2}]

?

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
Nick
  • 45
  • 5

2 Answers2

8

Looking at the rather dismal automatic placement of contour labels in the example Sin[x y], I thought it may be worth pointing out that you can often get better results with customized placement.

For this, I devised a function burnTooltip in this answer. Here is how to use it for this question:

Options[burnTooltips] = {ImageSize -> 360, 
   "LabelFunction" -> (Framed[#, FrameStyle -> None, 
       RoundingRadius -> 8, Background -> RGBColor[1, .8, .4]] &)};

burnTooltips[plot_, opt : OptionsPattern[]] := 
 DynamicModule[{ins = {}, wrapper = OptionValue["LabelFunction"], 
   toolRule = 
    Function[{arg}, 
     Tooltip[t__] :> 
      Button[Tooltip[t], 
       AppendTo[arg, 
        Inset[wrapper[Last[{t}]], MousePosition["Graphics"]]]], 
     HoldAll]}, 
  EventHandler[
   Dynamic@Show[plot /. toolRule[ins], Graphics@ins, 
     ImageSize -> OptionValue[ImageSize]], {"MouseUp", 
     2} :> (toolRule = {} &)]]

f[x_, y_] := Sin[x y]
p = ContourPlot[f[x, y], {x, -2, 2}, {y, -2, 2}, 
   ContourLabels -> Automatic];

burnTooltips[p]

tooltipburned

When you execute the last line, the plot appears and tooltips will be shown when you hover over the contours. If you see a tooltip in a location that you like, click the mouse. Repeat this for as many labels as you need. Every time you click, a new label will be added permanently at the mouse position. When you're done, you have to right-click on the plot. That will end the dynamic interactivity and burn the existing labels in place.

Jens
  • 97,245
  • 7
  • 213
  • 499
4
f[x_, y_] := Sin[x y]
ContourPlot[f[x, y], {x, -2, 2}, {y, -2, 2}, ContourLabels -> All]

Mathematica graphics

Or if you want only some of them:

f[x_, y_] := Sin[x y]
ContourPlot[f[x, y], {x, -2, 2}, {y, -2, 2}, 
            ContourLabels -> (If[Abs@#3 <= .25, Text[#3, {#1, #2}]] &)]

Mathematica graphics

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453