Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js: alternative to selecting elements by data attributes?

Tags:

d3.js

I'm using D3.js to build a circular heat chart, and I want to add events so that when I mouseover any section of the chart, all the elements at the same angle also highlight. (Like the mouseover events on this Guardian visualisation.)

At the moment, I'm doing this by explicitly adding data attributes to the HTML for every 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 by 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 actually the correct way to do things in D3? It feels to me like there "ought" to be a way to select the path based only on the data stored in the DOM, not on explicit data attributes.

like image 499
Richard Avatar asked Aug 05 '13 11:08

Richard


1 Answers

If you store the reference 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');
});
like image 158
amakhrov Avatar answered Nov 15 '22 11:11

amakhrov