5
$\begingroup$

I have a 2D scatter plot. Now I want to select a circular region in this plot and use the data inside the circular region for further analysis. Is there any way to do that?

$\endgroup$
9
$\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$
  • $\begingroup$ Your last line could be a bit simpler ListPlot[{pts, good}, AspectRatio -> Automatic, Epilog -> Circle[center, radius]] ;-) $\endgroup$ – Vitaliy Kaurov Apr 18 '18 at 20:04
  • $\begingroup$ That's right :) Could you explain why AspectRatio -> Automatic is not the same as default? $\endgroup$ – anderstood Apr 18 '18 at 20:34
  • $\begingroup$ This should give you a hint: GoldenRatio AspectRatio /. AbsoluteOptions[ListPlot[{}]] $\endgroup$ – Vitaliy Kaurov Apr 18 '18 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 Apr 19 '18 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$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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