score:2

Accepted answer

the fill of the arc is determined by the color() function on this line:

.style("fill", function(d) { return color(d.data.key); });

instead of using a function, we can pick from an array of colors based on the index. modify the above line to read:

.style("fill", function(d, i) { return color[i]; });

now we need to change the list of available colors based on the number of data points (number of keys in the data object). above the color() function, add:

var datasize = object.keys(getdata()).length
var color = d3.scale.category20(); // this line was already here

finally, we need to change the color variable from a function to an array. the array will vary based on the datasize, so a switch statement works great here. replace the color definition:

var color;

switch (datasize) {
  case 2:
    color = ['green' , 'gray'];
    break;
  case 3:
    color = ['green', 'red', 'yellow'];
    break;
}

this will give you green and gray when there are only two datapoints; and green, red, and yellow when there are 3 data points. you can add more cases for more amounts of data points.

everything in one jsfiddle.

with two data points:

donut chart showing two data points

with three data points:

donut chart showing two data points


edit: since you are using more than one chart and set of data on the same page, you will need to move this whole block to inside the object.render() function:

var datasize = object.keys(getdata()).length;
var color;

switch (datasize) {
  case 2:
    color = ['green' , 'gray'];
    break;
  case 3:
    color = ['green', 'red', 'yellow'];
    break;
}

and then change the datasize variable to get the length of the passed in data object's keys:

var datasize = object.keys(data).length;

new complete jsfiddle.


Related Query