2
$\begingroup$

In this very simple example the helpful function VoronoiMeshworks as expected. Every point pts is shown with a polygonal surrounding area.

pts = RandomReal[{-1, 1}, { 5, 2}];
mesh = VoronoiMesh[pts];
Show[mesh, Graphics[{Red, Point[pts]}]]

enter image description here

But if I try to plot the single elements to my surprise I get a list of plots which show some of the "inner" points lying outside the polygons!

pmesh = MeshCoordinates[mesh];
index = MeshCells[mesh, 2][[All, 1]];
elem = Map[Polygon[pmesh[[#]]] &, index]; (* polygons*) 



GraphicsRow@MapThread[Graphics[{col = RandomColor[], Point[#1], FaceForm[None],EdgeForm[col], #2}] &, {pts, elem}]

enter image description here

How can that be? Thanks!

$\endgroup$
2

1 Answer 1

8
$\begingroup$

Since Version 12.1, we can use NearestMeshCells to find the indexes of the polygon to which the points belong.

Clear[pts,mesh,indexs];
pts = RandomReal[{-1, 1}, {5, 2}];
mesh = VoronoiMesh[pts, Epilog -> {Red, Point[pts]}]
indexes = Flatten[NearestMeshCells[{mesh, 2}, #] & /@ pts, 1]

{{2, 2}, {2, 3}, {2, 1}, {2, 5}, {2, 4}}.

GraphicsRow@
 MapThread[
  Graphics[{col = RandomColor[], Point[#1], FaceForm[None], 
     EdgeForm[col], #2}] &, {pts, MeshPrimitives[mesh, indexes]}]

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.