Reputation: 587
I am experimenting with the d3 code for the radial tree found here: https://bl.ocks.org/mbostock/4063550
I'd like to make it so that the links leading from (and the corresponding nodes they connect to) of the first 10 child nodes are different colors. For example, all links and nodes coming from "animate" would be red, "data" orange, "display" yellow, and so on.
I'm brand new to this, so I apologize if I didn't explain this very well.
What I tried so far was adding code under this section:
node.append("circle")
.attr("r", 2.5);
I sort of just guessed how to designate a color to a specific node, and needless to say it didn't work.
Thanks for your help!
Upvotes: 3
Views: 866
Reputation: 1787
A solution which would extend to other datasets would be a recursive function, eg
http://blockbuilder.org/tomshanley/f73a13c5b5981fe97e6bf4dad1f52238
Relevant code:
let colour = d3.scaleOrdinal(d3.schemeCategory20)
function findColour(d) {
let c = "";
if (d.depth == 0 || d.depth == 1) {
c = colour(d.id);
}
else {
c = findColour(d.parent);
}
return c;
}
node.append("circle")
.attr("r", 2.5)
.style("fill", findColour)
Upvotes: 2
Reputation: 32327
Using the sample you provided in the question you can color the nodes like below:
node.append("circle")
.attr("r", 2.5)
.style("fill", function(d) {
if (d.id.startsWith("flare.animate")){
return "orange";
}
if (d.id.startsWith("flare.vis")){
return "red";
}
if (d.id.startsWith("flare.util")){
return "blue";
}
if (d.id.startsWith("flare.scale")){
return "maroon";
}
if (d.id.startsWith("flare.query")){
return "limegreen";
}
if (d.id.startsWith("flare.physics")){
return "deeppink";
}
if (d.id.startsWith("flare.flex")){
return "coral";
}
if (d.id.startsWith("flare.display")){
return "purple";
}
if (d.id.startsWith("flare.data")){
return "cyan";
}
});
working code here
Upvotes: 3
Reputation: 1591
You are on right track. Add the color property when appending the circles
node.append("circle")
.attr("r", 2.5)
.style("fill", function(d) { color = "black";
// your color logic based on property of d
if(d.name == "animate") color = "red";
if(d.name == "data") color = "orange";
.
.
return color});
Upvotes: -1