liveBook · Manning

Selection.attr()

As explained in D3.js in Action, Third Edition

A D3 selection method that gets or sets attributes on elements in a selection, optionally deriving values from bound data.

selection.attr() sets or modifies an attribute on every element in a D3 selection. Pass the attribute name first and its value second; the value may be constant or computed by an accessor function. section 2.5 section 2.7

Create a responsive SVG

Set the SVG viewBox with a four-number value: d3.select(".responsive-svg-container").append("svg").attr("viewBox", "0 0 1200 1600"); Use the case-sensitive CamelCase spelling viewBox so the browser recognizes the attribute. section 2.5

Chain attr() calls to build and style SVG shapes:

  • Pass an accessor such as d => d.count to derive an attribute from bound data. 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)

Shows a complete data-driven chain that assigns class, width, and height attributes to joined rectangles. section 3.3.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains fixed values, accessor functions, bound data, indexes, and conditional attributes through bar-chart implementation.
Examples
Uses a responsive SVG viewBox, rectangle geometry, data-sized bars, indexed positioning, and conditional bar colors.
What it assumes
Assumes basic SVG attributes, D3 selections, DOM elements, and JavaScript functions while teaching data access from zero.
What you can do after
Apply it via D3 to create SVG elements and assign fixed or data-derived attributes in chart construction.
How it connects
Connects D3 selections with SVG attributes, data binding, accessor functions, DOM manipulation, and template literals.

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.