10
$\begingroup$

I am reading a file with 4 columns (índex and 3 coordinates) and I want to plot spheres at these positions:

data = Import["positions.txt", "Table"];
ballspec = {1.*#1, {#2, #3, #4}} & @@@data[[All, 1 ;; 4]];
plot = Graphics3D[{RGBColor[#3], {Opacity[.7], 
       Sphere[{#2}, .25]}} & @@@ ballspec, Axes -> False];
Show[plot]

but I would also like to add lines connecting the nearest neighbor points, how could I proceed?

$\endgroup$
1

2 Answers 2

13
$\begingroup$

Perhaps NearestNeighborGraph?:

NearestNeighborGraph[pts]

enter image description here

$\endgroup$
11
$\begingroup$

You can use Nearest:

pts = RandomReal[1, {100, 2}];
pairs = Transpose[{pts, Nearest[pts, pts, 2][[All, 2]]}];
Graphics[{Point[pts], Line[pairs]}]

Mathematica graphics

or in 3D

pts = RandomReal[1, {100, 3}];
pairs = Transpose[{pts, Nearest[pts, pts, 2][[All, 2]]}];
Graphics3D[{Point[pts], Line[pairs]}]

Mathematica graphics

or with colours

pts = RandomReal[1, {100, 3}];
colors = RandomReal[1, {100}];
pairs = Transpose[{pts, Nearest[pts, pts, 2][[All, 2]]}];
Graphics3D[{Transpose@{Hue /@ colors, Sphere[#, 0.025] & /@ pts}, 
  AbsoluteThickness[3], Line[pairs]}]

Mathematica graphics

$\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.