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
