D3.js: an alternative to selecting elements with data attributes?

I use D3.js to create a heat pie chart, and I want to add events so that when you hover over any section of the chart, all elements are also highlighted at the same angle. (Similar to mouseover events on this Guardian visualization .)

I am currently doing this by explicitly adding data attributes in the HTML for each path element:

  g.selectAll("path").data(data) .enter().append("path") .attr("d", d3.svg.arc().innerRadius(ir).outerRadius(or).startAngle(sa).endAngle(ea)) .attr("data-pathnumber", function(d) { return d.pathNumber }); 

And then my mouseover event selects the data attribute:

 d3.selectAll("#chart4 path").on('mouseover', function() { var d = d3.select(this).data()[0]; d3.selectAll('path[data-pathnumber="' + d.pathNumber + '"]').attr('fill', 'black'); }); 

However, is this really the right way to do something in D3? It seems to me that “should” be a way to choose a path based only on data stored in the DOM, and not on explicit data attributes.

+6
source share
1 answer

If you keep a link to your paths, you can use selection.filter here:

 var paths = g.selectAll("path").data(data) .enter().append("path") .attr("d", d3.svg.arc().innerRadius(ir).outerRadius(or).startAngle(sa).endAngle(ea)) ; 

Mouseover:

 d3.selectAll("#chart4 path").on('mouseover', function(thisData) { paths .filter(function (d) { return d.pathNumber === thisData.pathNumber; }) .attr('fill', 'black'); }); 
+9
source

Source: https://habr.com/ru/post/951034/


All Articles