5
$\begingroup$

Suppose I want contour plot of $x^2-y^2$, for $x,y\in[0,1]$ (my actual function is more complicated). Over this interval, $x^2-y^2$ is sometimes positive and sometimes negative. Using ContourPlot I get all the contours, negative as well as positive.

But what if I wanted only those contours with values $\geq 0$ to show, while those contours whose value is less than zero are not displayed or (worst case) shown by the same color (say white). I doubt if this is possible at all, but any help is much appreciated.

$\endgroup$
2
  • $\begingroup$ ContourPlot[ ConditionalExpression[x^2 - y^2, x^2 >= y^2], {x, 0, 1}, {y, 0, 1}] or ContourPlot[x^2 - y^2, {x, 0, 1}, {y, 0, 1}, RegionFunction -> (#^2 >= #2^2 &)]? $\endgroup$
    – kglr
    Commented Nov 23, 2017 at 11:01
  • $\begingroup$ @kglr Awesome. Why not post it as an answer? $\endgroup$
    – Deep
    Commented Nov 23, 2017 at 11:06

2 Answers 2

8
$\begingroup$

You can use the option RegionFunction:

ContourPlot[x^2 - y^2, {x, 0, 1}, {y, 0, 1}, RegionFunction -> (#^2 >= #2^2 &)]

enter image description here

Or use ConditionalExpression

ContourPlot[ConditionalExpression[x^2 - y^2, x^2 >= y^2], {x, 0, 1}, {y, 0, 1}, 
 Contours -> 4]

enter image description here

$\endgroup$
2
  • $\begingroup$ does not this plot restricting the domain of the function? I understand that the OP ask for showing the contours that indicate levels $f>0$ while plotting the function over the whole domain... $\endgroup$ Commented Nov 23, 2017 at 19:32
  • $\begingroup$ @JoséAntonioDíazNavas, i agree with you. That's why i posted this as a comment and posted as answer per OP's suggestion. $\endgroup$
    – kglr
    Commented Nov 23, 2017 at 23:56
3
$\begingroup$

Maybe this:

ContourPlot[x^2 - y^2, {x, 0, 1}, {y, 0, 1},Contours -> Rescale@Range[#]] & /@ {5, 10, 20}

enter image description here

or:

ContourPlot[x^2 - y^2, {x, 0, 1}, {y, 0, 1}, ColorFunction -> (Blend[{White, Blue}, #] &), 
Contours -> Rescale@Range[#]] & /@ {5, 10, 20}

enter image description here

Even the contours can be customised, of course. In this case continuous for $f\geq 0$ and Dashed for $f<0$:

Show[{ContourPlot[x^2 - y^2, {x, 0, 1}, {y, 0, 1}, ContourStyle -> None], 
ContourPlot[Evaluate@((x^2 - y^2 == #) & /@ Range[-1, 1, 0.1]), {x, 0, 1}, {y, 
0, 1}, ContourStyle -> (If[#>=0, {Directive[Black]}, {Directive[Black, Dashed]}] & /@ 
  Range[-1, 1, 0.1])]}]

enter image description here

$\endgroup$
1
  • $\begingroup$ +1 Your answer is helpful too. Thank you very much. $\endgroup$
    – Deep
    Commented Nov 24, 2017 at 4:49

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.