0
$\begingroup$

I have a list of linear inequalities which describe a (polygonal) region. I can use RegionPlot to visualize this region; but I'd also like to overlay this plot with the lines corresponding to each inequality. ContourPlot works for drawing the lines, but only if I put my list of equations as it's argument -- if I put a variable holding the list of equations I get nothing out.

constraints = {
    x <= 2,
    x + 2 y >= 2,
    x + 2 y <= 6,
    x - 2 y >= -2,
    3 x + 6 y <= 18
}
region = And @@ constraints
equations = constraints /. { LessEqual -> Equal, GreaterEqual -> Equal}

p1 = RegionPlot[region, {x, -1, 3}, {y, -1, 3}]

This shows the region nicely shaded in blue. The variable "equations" is set to a list of equations of the lines I'd like to highlight; it's value is

{x == 2, x + 2 y == 2, x + 2y == 6, x - 2y == -2, 3x + 6y == 18}

Now I try to plot these lines:

p2 = ContourPlot[equations, {x, -1, 3}, {y, -1, 3}]

This results in an empty plot!

However, if I copy-and-paste the value of "equations" right into the code, it renders a nice plot:

p2 = 
  ContourPlot[{x == 2, x + 2y == 2, x + 2y == 6, x - 2y == -2, 3x + 6y == 18},
    {x, -1, 3}, {y, -1, 3}]

To wrap up, I overlay the two plots:

Show[p1, p2]

Why does ContourPlot see a difference between the two invocations? My understanding is that they should be equivalent.

$\endgroup$
2
2
$\begingroup$
constraints = {x <= 2, x + 2 y >= 2, x + 2 y <= 6, x - 2 y >= -2, 3 x + 6 y <= 18};
region = And @@ constraints;
equations = constraints /. {LessEqual -> Equal, GreaterEqual -> Equal};

p1 = RegionPlot[region, {x, -1, 3}, {y, -1, 3}];
p2 = ContourPlot[Evaluate@equations, {x, -1, 3}, {y, -1, 3}];
Show[p1, p2]

Mathematica graphics

$\endgroup$
3
  • $\begingroup$ Thank you, belisarius. This solves my problem. But why was it a problem in the first place? $\endgroup$
    – Jim Meier
    Mar 11 '13 at 3:20
  • $\begingroup$ @JimMeier The problem is related with Plot[] functions not being aware that equations is a List. Evaluate[] solves that. There is a more detailed explanation made by Leonid somewhere in the site, but I can't find it right now. Follow the links in the comments posted by Mr.Wizard under your question. $\endgroup$ Mar 11 '13 at 3:31
  • $\begingroup$ I'll have to do some reading of this, apparently I do not understand Mathematica's variables and pattern matching well enough. Thanks again. $\endgroup$
    – Jim Meier
    Mar 11 '13 at 5:51

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