liveBook · Manning

Accessor method

As explained in D3.js in Action, Third Edition

An accessor function is a callback that receives a bound datum and often its index to derive a value for a D3 operation.

An accessor function is a callback that receives a datum and returns the value a D3 operation should use. It lets one operation derive different results from each data object instead of assigning one fixed value to every element. section 3.3.1 section 3.2.3

Use accessors wherever a D3 operation needs a value calculated from data:

  • Pass d => d.count to d3.max(), d3.min(), or d3.extent() to compare the count property. section 3.2.3
  • Return values from attr() callbacks, such as d.count for rectangle width or (d, i) => (barHeight + 5) * i for vertical position. section 3.3.1
  • Map fields to area-generator coordinates with x(), y0(), and y1(), defining horizontal and lower and upper vertical boundaries. section 4.3.1

Sizing and positioning bars

After binding the dataset, each rectangle can read its own object: .attr("width", d => d.count) uses the technology count, while .attr("y", (d, i) => (barHeight + 5) * i) uses the element index to place the bar. The same pattern can return a conditional fill, such as a different color for D3.js. section 3.3.1

const barHeight = 20;
svg
  .selectAll("rect")
  .data(data)
  .join("rect")
    .attr("class", d => {
      console.log(d);
      return "bar";
    })
    .attr("width", d => d.count)
    .attr("height", barHeight)
    .attr("x", 0)
    .attr("y", (d, i) => (barHeight + 5) * i)

The complete rectangle chain shows accessors reading each datum for width and the index for vertical placement. section 3.3.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains callback parameters and return values through bar-chart code, then extends the pattern to area-generator boundaries.
Examples
Demonstrates technology counts, bar dimensions and positions, conditional colors, and minimum-to-maximum temperature areas.
What it assumes
Assumes basic JavaScript functions, arrays, object properties, and D3 data binding while demonstrating datum and index parameters.
What you can do after
Apply accessors via D3 methods to calculate values for each datum, index-based layout, conditional styling, and chart geometry.
How it connects
Connects accessor functions with D3 statistics, data binding, SVG attributes, arrow functions, and area generators.

Also explained in

Compare how 14 books explain accessor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.