0

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.

Community
  • 1
  • 1
Jefftopia
  • 2,105
  • 1
  • 26
  • 45

1 Answers1

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.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Two comments. First, I wasn't able to get the desired functionality from these code snippets, but I got closer to where I wanted, and it probably didn't work 100% because I'm a newb. As such, I'm giving you the green check. That said, with a large number of categories, I'm thinking that a traditional legend is undesirable - it's just ugly on screen. Do you have any suggestions for a key to a large sequence diagram? – Jefftopia Feb 02 '14 at 05:15
  • Well, it would have helped if you had posted the code and data you were actually using for this -- I tried to extrapolate from the example you've linked to, but obviously I can only guess what you're actually doing. For a large number of categories, I probably would do away with the legend completely and show the key on mouseover or something like that. – Lars Kotthoff Feb 02 '14 at 11:47
  • I'll put my stuff in a fiddle next time. For now, I think you are right though - hovers are the way to go. The d3 demo I linked to already have these hovers, and they're quite nice. – Jefftopia Feb 03 '14 at 20:44