2014-10-06 125 views
1

在这个pie-chart fiddle我想根据我的json的数据(类型和子类型)对切片着色。d3饼图颜色分配到圆弧

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,所以我可以确定使用什么颜色。我只能访问馅饼()函数返回(即value/startAngle/endAngle

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

谢谢。然后使用该数据(如颜色设置功能)

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

回答

1

您可以通过“穿越了”的DOM到你绑定到父节点的数据访问数据设置颜色:

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/

+0

这看起来不错。我不知道你可以做到这一点。但请问,为什么我在0时回到白色?它反映在饼图中,这不完全是我想要的。 – gaitat 2014-10-06 15:03:22

+0

好的,我明白了。变量'i'(在小提琴中)对应于正在绘制的路径。 – gaitat 2014-10-06 15:15:11

+0

这只是一种区分第一个饼图片段和第二个饼图片段的方法,因为您尚未指定要如何做到这一点 – Josh 2014-10-06 19:42:54