Very often I encounter a situation that I want to select some points inside certain areas of a plot. For example,

p1 = Graphics[Point[Table[{Random[], Random[]}, {200}]]]

will give a plot. If I use MMA's drawing tool to draw a region in the plot,

p2=enter image description here

how I get the plot dynamically updated so that it shows only the points inside that region?

Here is my attempt. I use the function inPolyQ by rm -rf at here to test whether the points is inside the region or not.

lines = First[Cases[p2, Line[x_] :> x, \[Infinity]]];
pts = First[Cases[p2, Point[x_] :> x, \[Infinity]]];
inPolyQ[poly_, pt_] := Graphics`Mesh`PointWindingNumber[poly, pt] =!= 0
slctPts = Select[pts, inPolyQ[lines, #] &];
Graphics[{Point[slctPts], Line[lines]}, AbsoluteOptions[p1]]

the out put is enter image description here

I have two problems:

  1. How can I change it to a efficient function that can do all this dynamically on a plot(or may density plot), and with the option to output the selected data points?
  2. There is a problem that sometimes I actually select more points than I want. Like in the example, there are two points outside the region are also selected. Is there a way to solve that?


  • $\begingroup$ Please see the duplicate question above. The answers there solve this exact problem. As a side note, you could also use Graphics`Mesh`InPolygonQ (with the same syntax). I mentioned this in a comment under my answer $\endgroup$
    – rm -rf
    Feb 23, 2013 at 20:22
  • $\begingroup$ @rm-rf thanks for point this out, I tried to search some words, but this didn't come up. It's exactly what I'm looking for. You were so fast! $\endgroup$ Feb 23, 2013 at 20:43
  • $\begingroup$ @xslittlegrass WoW, I like your method to choose region using drawing tool, it's much more flexible to use linesegment or freehandline than polygon. And so smart to extract lines and pts from the plot. Why didn't you post an answer to that question? $\endgroup$
    – matheorem
    Dec 11, 2013 at 5:16


Browse other questions tagged or ask your own question.