6
$\begingroup$

I have a 2D scatter plot. I want to define a circular region in this plot and use the data points inside the circular region for further analysis. Is there any way to do this and plot the two set of points?

$\endgroup$

4 Answers 4

10
$\begingroup$

Using Select and Norm:

pts = RandomReal[10, {1000, 2}];
center = {5, 3};
radius = 2;
good = Select[pts, Norm[# - center] < radius &];

Show[ListPlot[{pts, good}], Graphics@Circle[center, radius],  AspectRatio -> 1]

enter image description here

$\endgroup$
4
  • $\begingroup$ Your last line could be a bit simpler ListPlot[{pts, good}, AspectRatio -> Automatic, Epilog -> Circle[center, radius]] ;-) $\endgroup$ Commented Apr 18, 2018 at 20:04
  • $\begingroup$ That's right :) Could you explain why AspectRatio -> Automatic is not the same as default? $\endgroup$
    – anderstood
    Commented Apr 18, 2018 at 20:34
  • $\begingroup$ This should give you a hint: GoldenRatio AspectRatio /. AbsoluteOptions[ListPlot[{}]] $\endgroup$ Commented Apr 18, 2018 at 21:46
  • $\begingroup$ @VitaliyKaurov I don't know why I expect Automatic settings to be default. A bit like in NDSolve, Method -> Automatic does not change anything (afaik). $\endgroup$
    – anderstood
    Commented Apr 19, 2018 at 1:14
8
$\begingroup$

I'd use Nearest instead of Select, as it is much faster. Compare

pts = RandomReal[10, {10^5, 2}];
center = {5, 3};
radius = 2;

sub1 = Select[pts, Norm[# - center] < radius &]; // AbsoluteTiming

{0.538735`, Null}

sub2 = Nearest[pts, center, {All, radius}]; // AbsoluteTiming

{0.002293`, Null}

ListPlot[{pts, #}, ImageSize -> 400, AspectRatio -> Automatic] & /@ {sub1, sub2}

enter image description here

The points sets might differ due to different boundary inclusion interpretation by Nearest and Select. But those could be easily adjusted by the radius value.

$\endgroup$
1
$\begingroup$

Using RegionMember:

SeedRandom[1];
pts = RandomReal[10, {10^5, 2}];
center = {5, 5};
radius = 2;
good = Select[pts, RegionMember[Disk[center, radius]]];
outside = Complement[pts, good];

ListPlot[{outside, good}
 , AspectRatio -> Automatic
 , PlotStyle -> {Directive[AbsolutePointSize[1], Red], 
   Directive[AbsolutePointSize[1], Darker@Green] }
 , Epilog -> {Circle[center, radius]
   }
 ]

enter image description here

$\endgroup$
1
$\begingroup$

Using GroupBy

pts = RandomReal[10, {10^5, 2}];
f[lst_, c_, r_] := GroupBy[lst, (# - c) . (# - c) < r^2 &];
ListPlot[f[pts, {5, 3}, 2], AspectRatio -> Automatic]

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.