I am computing a voronoi diagram from a set of points as follows:
from scipy.spatial import Voronoi
import numpy as np
np.random.seed(0)
points = np.random.uniform(-0.5, 0.5, (100, 2))
# Compute Voronoi
v = Voronoi(points)
voronoi_plot_2d(v)
plt.show()
This creates an image as follows:
As one can see, this is creating vertices which are going to infinity (dashed lines) and also beyond the original bounding box for the points which is:
bbox = np.array([[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]])
What I would like to do is clip the voronoi diagram to this bounding box i.e. project the out of bounds and infinite vertices onto the appropriate locations on this bounding box. So the vertices would need to be rearranged and projected back to the proper intersection points from infinity or the finite vertices but which are out of bounds from my clipping region.
It can be easyly be done with Shapely. You can install it from Conda Forge:
conda install shapely -c conda-forge
Code you need at github.gist, based on answer by @Gabriel and @pv.: