How to create legend for D3 Sequence Sunburst?

限于喜欢 提交于 2020-01-06 15:08:11

问题


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.



来源:https://stackoverflow.com/questions/21502187/how-to-create-legend-for-d3-sequence-sunburst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!