5
$\begingroup$

I want to

$1.$ highlight a contour line in a ContourPlot by coloring it, and

$2.$ obtain the area surrounded by that contour line.

For example, I want to color the contour of $-0.72$ in the following figure to red, then obtain the area of the inner part of the contour of $-0.72$.

$Note:$

$1.$ I am looking for a general method because in my real problem the object function (here Cos[x] + Cos[y]) was obtained numerically as an InterpolatingFunction, and

$2.$ the region of interest surrounded by the contour line is an irregular region.

ContourPlot[Cos[x] + Cos[y], {x, 0, 4 Pi}, {y, 0, 4 Pi}, 
Contours -> 10, ContourStyle -> {AbsoluteThickness[1], Black}, 
PlotLegends -> Automatic]

enter image description here

Thank you!

$\endgroup$
7
  • $\begingroup$ I would b = ContourPlot[{Cos[x] + Cos[y] == -0.72}, {x, 0, 4 Pi}, {y, 0, 4 Pi}, ContourStyle -> {AbsoluteThickness[5], Red}] and Show[a,b] it together with your plot a. $\endgroup$
    – corey979
    Sep 12, 2016 at 9:21
  • $\begingroup$ What if the contour you want to highlight is not there? E.g. -0.9 is not marked there but have you known before plotting? Do you want to force it to be created? How should it work with Contours spec you use. $\endgroup$
    – Kuba
    Sep 12, 2016 at 9:22
  • $\begingroup$ @Kuba, in general, I will plot it using black color with specified number for Contours and determine which contour I'd like to highlight :) then I will use a certain trick to color it to red. $\endgroup$
    – lxy
    Sep 12, 2016 at 9:30
  • $\begingroup$ @jsxs Unrelated question but, are you by any chance working with acoustic fields? $\endgroup$
    – Keine
    Sep 12, 2016 at 14:37
  • 1
    $\begingroup$ Related: mathematica.stackexchange.com/questions/28762/… $\endgroup$
    – Michael E2
    Sep 13, 2016 at 1:10

1 Answer 1

4
$\begingroup$

Single out one contour:

ContourPlot[Cos[x] + Cos[y] == 0.72, {x, 0, 4 Pi}, {y, 0, 4 Pi}, ContourStyle -> Red]

enter image description here

Use Show to combine several graphics outputs.

By visually inspecting the result, we can determine a bounding box for the contour in the middle: it is $([\pi,3\pi], [\pi, 3\pi])$.

Comparing with your original contour plot, we see that the enclosed region is defined by the equation Cos[x] + Cos[y] > 0.72. In other cases we might need to use < instead.

Define it as a region (version 10 and later):

reg = ImplicitRegion[Cos[x] + Cos[y] > 0.72, {{x, Pi, 3 Pi}, {y, Pi, 3 Pi}}];

Find the area: Area[reg]. Also look up RegionMeasure.

Plot it: RegionPlot[reg]

In versions before 10, find the area:

NIntegrate[Boole[Cos[x] + Cos[y] > 0.72], {x, Pi, 3 Pi}, {y, Pi, 3 Pi}]

Plot it:

RegionPlot[Cos[x] + Cos[y] > 0.72, {x, Pi, 3 Pi}, {y, Pi, 3 Pi}]
$\endgroup$
0

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.