问题
Developing a d3 bubble chart by following the example posted at http://bl.ocks.org/mbostock/4063269:
My dataset is has one branch but many children (see sample below). All my bubbles are displayed in the same color. Is it possible to modify the logic to generate different color bubbles for each children in the same branch? If so, any assistance would be much appreciated.
{
"name": "mydata",
"children": [
{"name": "test1", "size": 5},
{"name": "test2", "size": 10},
{"name": "test3", "size": 15},
{"name": "test4", "size": 20}
]
}
回答1:
Simply pass a different datum to the color function, e.g. the index:
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d, i) { return color(i); });
or, for your data, size:
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { return color(d.size); });
回答2:
To pic random colors user this
node.append("circle").attr("r", function(d) {
return d.r;
}).style("fill", function(d) {
return color(Math.random());
});
回答3:
Two concept we can use for fill color
1. var colour = d3.scale.category20(); // it will set random color from 20 color list.
2.Its easy to set custom color based on text value which comes from JSON Data .. i have used below concept
.style("fill", function (d) {
if (d.item.text == "InProgress") {
return "#2DD7EB"
} else if (d.item.text == "Signed Off") {
return "#3CEB2D"
} else if (d.item.text == "Pending") {
return "#F55431"
}
来源:https://stackoverflow.com/questions/20004063/how-to-display-d3-bubbles-in-different-colors-for-a-dataset-with-one-branch-and