1
$\begingroup$

I need label some ContourPlots with different color and position. My example is:

ContourPlot[6x+9y, {x, -2, 8}, {y, -2, 12}, Axes -> True, Frame -> False, 
            Contours -> {{30, Directive[Red, Thick]}, {52.5, Directive[Green, Thick]}},
            ContourShading -> None, ContourLabels -> True]

I want label of contour 30 appears in red (and bold?) and contour 52.5 in green. Also, I need position change for labels stay inside frame.

Thank in advance

$\endgroup$

3 Answers 3

2
$\begingroup$

An alternative way to post-process ContourPlot output to modify label positions using the function LineScaledCoordinate from the GraphUtilities package:

Needs["GraphUtilities`"]
ClearAll[modifyLabels]
modifyLabels[styles__:24] := Quiet[Normal[#] /. {Text[__] :> Sequence[], 
 t : Tooltip[a_, b_] :> {t, Text[Style[b, {a[[-2]], styles}], 
  LineScaledCoordinate[a[[-1, 1]], .5], Background -> White]}}] &

Example:

It is essential that the we use ContourLabels -> All in the input contour plot for the function modifyLabels to work:

cp = ContourPlot[6 x + 9 y, {x, -2, 8}, {y, -2, 12}, Axes -> True, 
   Frame -> False, Contours -> {{30, Directive[Red, Thick]}, {52.5, 
      Directive[Green, Thick]}}, ContourShading -> None,  ContourLabels -> All];

modifyLabels[][cp]

enter image description here

$\endgroup$
0
$\begingroup$

There was a similar (if not duplicate) question How to add Contour labels in the desired place?

I am modifying my earlier answer to suit your requirement.

labels = {Style["52.5", 14, Green, Bold], Style["30", 12, Red, Bold]};

plot = ContourPlot[6 x + 9 y, {x, -2, 8}, {y, -2, 12}, Axes -> True, Frame -> False, 
           Contours -> {{30, Directive[Red, Thick]}, {52.5, Directive[Green, Thick]}},
           ContourShading -> None, ContourLabels -> True];

lines = Cases[plot // Normal, Line[x_] :> x, Infinity]; (*get the contour lines*)
nc = Length[lines];
cen = Nearest[lines[[#]], Mean@lines[[#]]][[1]] & /@ Range[nc];
Show[plot, Epilog -> ({Text[labels[[#]], cen[[#]] + {0, 0.5}]} & /@ 
Range[1, nc])]

enter image description here

Remove ContourLabels->True from your main plot if you don't want the black contour labels.

$\endgroup$
0
$\begingroup$
ContourPlot[6 x + 9 y, {x, -2, 8}, {y, -2, 12},
 Axes -> True, Frame -> False,
 Contours -> {
   {30, Directive[Red, Thick]},
   {52.5, Directive[Green, Thick]}},
 ContourShading -> None,
 ContourLabels -> (Style[
     Text[#3, {#1, #2}, Background -> White],
     14, Bold, If[#3 == 30, Red, Green]] &),
 PlotRange -> {{-2.3, 8}, {-2, 8}}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.