1
votes

In this pie-chart fiddle I would like to color the slices based on the data (type and subtype) of my json.

var data = {
    "details": [
        { "id": 1, "name": "AAA", "pcArray": [25,75], "type": "c", "subtype": "p", },
        { "id": 2, "name": "BBB", "pcArray": [25,175], "type": "c", "subtype": "r", },
        { "id": 3, "name": "CCC", "pcArray": [5,95], "type": "e", "subtype": "p", },
        { "id": 4, "name": "DDD", "pcArray": [10,30], "type": "e", "subtype": "r", },
        { "id": 5, "name": "EEE", "pcArray": [0,30], "type": "c", "subtype": "r", },
    ],
};

So I would like for example

for type: "c" and subtype: "p" use color(0)
for type: "c" and subtype: "r" use color(1)
for type: "e" and subtype: "p" use color(2)
for type: "e" and subtype: "r" use color(3)

I have allocated the color vector like this

// 0: blue, 1: orange, 2: green, 3: red
var color = d3.scale.category10().domain(d3.range(0,3));

but when it is time to draw the paths I don't have access to my original json so I can deside what color to use. I can only access what the pie() function returns (ie. value / startAngle / endAngle)

So my question is how can I access my original data at the time the path is being drawn so that I can determine what color to use when drawing the slice?

Thank you.

1

1 Answers

1
votes

You can access the data by 'traversing up' the DOM to the data you've bound to the parent node: (in the function where the color is set)

var d = d3.select(this.parentNode.parentNode).datum();

Then using that data to set the color:

var colorList = d3.scale.category10().range();
if (d.type === "c") {
  if (d.subtype === "p") return colorList[0];
  if (d.subtype === "r") return colorList[1];
}
else if (d.type === "e") {
  if (d.subtype === "p") return colorList[2];
  if (d.subtype === "r") return colorList[3];
}

Updated fiddle here: http://jsfiddle.net/n4rba907/1/