How to create legend for D3 Sequence Sunburst?

2019-08-29 05:14发布

问题:

I'm modifying the original D3 Sequence Sunburst file to better suit my needs. The original colors variable is a hard-coded object. This clearly cannot be the best method. I'm using the flare.json example, which is larger, harder to read, and still much smaller than the json file I will be user after testing.

I'd like to randomly generate colors, apply them to each datum in the createvisualization function, but I'm new to D3, and do not know how to 1) fetch names (everything but the leaves) from the json file, and 2) pair them with their random color.

Edit:

Adding random colors and applying them turned out to be trivial,

var colors = d3.scale.category10();
...
.style("fill", function(d,i) { return colors(i); })

But I'm still note sure how to fetch the names of all non-leaves in the json, then create an array from both the random colors and the non-leaves.

Help here greatly appreciated.

回答1:

To get the names of all non-leaf elements, you can do something like this.

var names = [];

function getNames(node) {
  if(node.children) {
    names.push(node.name);
    node.children.forEach(function(c) { getNames(c); });
  }
}

getNames(root);

After running this code, names will contain all the names you want. To then generate a legend from that, you can use the names array as the data:

var gs = svg.selectAll("g.name").data(names).enter().append("g").attr("class", "name");
gs.append("rect")
  // set position, size etc
  .attr("fill", d);
gs.append("text")
  // set position etc
  .text(String);

This will append a g element for each name and within each g element, append a rect that is filled with the colour corresponding to the name and a text element that shows the name.