javascriptd3.jsstream-graph

d3.js: How to add a data key?


I'm learning D3.js and trying to get my head around data keys used with streamgraphs. I would like to adapt the official streamgraph example:

enter image description here

...so that each path has an explicit data key, and so that the mouseover logs the data key.

The official example adds paths as follows:

var area = d3.svg.area()
   .x(function(d) { console.log('x', d.data); return d.x * w / mx; })
   .y0(function(d) { return h - d.y0 * h / my; })
   .y1(function(d) { return h - (d.y + d.y0) * h / my; });
vis.selectAll("path")
 .data(data0) 
 .enter().append("path")
 .style("fill", function() { return color(Math.random()); })
 .attr("d", area);

I tried adapting the code as follows, but I'm not sure how to change the structure of data0 (currently an array of arrays) to achieve what I want:

vis.selectAll("path")
 .data(data0, function(d) { return d.name }) // Add key function
 .enter().append("path")
 .style("fill", function() { return color(Math.random()); })
 .attr("d", area)
 .on("mouseover", function (d,i) { 
     console.log("mouseover", d.name); // Log name property on mouseover
  });

As it stands, without my having made any changes to the structure of data0, it unsurprisingly does not work. How can I add a name property to data0 without also messing up the area and .data() functions?

UPDATE: To be a bit clearer: the D3 docs say that the area function is expecting a two-dimensional array. So if I change data0 from a two-dimensional array, to an array of objects, each with a name key and a data key, how can I also change what I pass to area?


Solution

  • The data in the example doesn't have a "name" property, so you would need to add that to the data to use it. The data keys you refer to are used when merging/updating data, i.e. you have drawn some paths already and then update (some of them). The .data() function will try to figure out what data is updated and what data is new. If that doesn't work for you, you can use the data key to help it, i.e. in your case tell it that things with the same name are the same data.