Search⌘ K

Accessor Functions

Explore how accessor functions in D3.js help bind complex data properties to SVG circle elements in scatter plots. Understand how these functions determine the positioning and size of each circle based on data values, enabling effective visualization of relationships like humidity and temperature.

We are going to learn about accessor functions and why we need an accessor function. An accessor function is a function that returns a property in an object. In our script, we have already done so much. The data has been retrieved, the dimensions are set, and we drew the image. The next step is to start drawing some shapes.

The next step

The first set of shapes we are going to draw are circles. The data in a scatter plot is represented by a group of dots. We can draw a dot with the <circle> element.

We already have an idea of how we can add circles to our image. Each circle we draw should be joined with the data in our dataset. We do not want to draw more circles than we have to, nor do we want to draw fewer circles than what is in our data.

Here is what we will do. We will create a selection of circles. D3 will return an empty selection because we have not drawn any circles in our image. Next, we will join the dataset with the empty selection. This will force D3 to put the dataset into an enter selection. From there, we can begin the process of drawing circles for each item in the enter selection. We are already familiar with this process. The difference is that we will be working with SVG instead of regular HTML elements.

Drawing the dots

At the bottom of the draw() function, we replaced the code we wrote for drawing a single circle. The code we replaced it with will draw a circle for each item in the dataset array.

We are accomplishing this task by making an ...