2014-10-06 85 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