Creating a Voronoi Diagram
D3 can generate a Voronoi diagram with a few functions and some data fed into it.
We'll cover the following...
We are going to create a Voronoi diagram. We will be using the D3 Delaunay library to help us generate a Voronoi diagram. By default, it is already included with our D3 project. We can begin using it immediately.
In the script, we will be writing our code at the bottom of the draw()
function. We are adding an interactive feature. Therefore, it will be one of the last steps for drawing a graph. We can set up interactions after everything else has been drawn.
Configuring the Voronoi diagram
We are going to define a variable called Delaunay. Its value will be the d3.Delaunay.from()
function.
const delaunay = d3.Delaunay.from(dataset,d => xScale(xAccessor(d)),d => yScale(yAccessor(d)),)console.log(delaunay)
The from()
function will loop through an array of data. For each item in the array, it will calculate the triangulation of each point. In other words, it will tell us the coordinates for drawing a partition for a specific point. The from()
function has three arguments. The first argument is the array of data. We will pass in the dataset
variable.
Next, it needs to know which property in our data will be used for the x coordinate. We are going to pass in an arrow function that accepts an argument called d
. The d
argument will reference the items in the array. As stated earlier, the from()
function loops through the array. We can use the d
argument to grab the object in the current iteration. This function needs to return an x coordinate. We can use the ...