const scores = [ { name: "Alice", score: 96 }, { name: "Billy", score: 83 }, { name: "Cindy", score: 81 }, { name: "David", score: 96 }, { name: "Emily", score: 88 } ]; const bar = d3.select(".chart") .append('svg') .attr('width', 225) .attr('height', 300) // 5 * 33 = 165 < 300 .selectAll("g") .data(scores) .enter() // In D3, the SVG is used as a generic container like a HTML
. .append("g") // D3 convention: d for data, i for index. // doesn't support x,y, but needs transform. // translate take a comma-separated list of x,y coordinates. .attr('transform', (d, i) => 'translate(0, ' + i * 33 + ')'); // Notice how we don't pass data again or use a loop: they are included in the selection. bar.append('rect') .style("width", d => d.score) .text(d => d.name) // classed('bar', true) to set, classed('bar', false) to remove. .attr("class", "bar") // Contrived example: '.bar:hover' in CSS would have been sufficient. // A fat arrow function would have a lexical this instead of the proper one. .on('mouseover', function (d, i, elements) { d3.select(this) .style('transform', 'scaleX(2)'); // Like 'this', 'elements' are plain DOM elements. d3.selectAll(elements) .filter(':not(:hover)') .style('fill-opacity', 0.2); }) .on('mouseout', function (d, i, elements) { d3.selectAll(elements) .style('fill-opacity', 1) .style('transform', 'scaleX(1)'); }) .on('click', (who) => console.log(`hi ${who.name}`)); bar.append('text') .attr('y', 20) .text(d => d.name);