d3饼图颜色分配给弧

时间:2014-10-06 13:44:45

标签: javascript d3.js pie-chart

在这个pie-chart fiddle中,我想根据我的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", },
    ],
};

所以我想举个例子

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)

我已经分配了这样的颜色矢量

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

但是到了绘制路径的时候,我无法访问原来的json,所以我可以决定使用什么颜色。我只能访问pie()函数返回的内容(即。value / startAngle / endAngle

所以我的问题是如何在绘制路径时访问原始数据,以便确定绘制切片时要使用的颜色?

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以通过将“遍历”DOM到您绑定到父节点的数据来访问数据:(在设置颜色的函数中)

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

然后使用该数据设置颜色:

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];
}

此处更新了小提琴:http://jsfiddle.net/n4rba907/1/