How to display d3 bubbles in different colors for a dataset with one branch and many children?

妖精的绣舞 提交于 2019-12-08 01:54:40

问题


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

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