简体   繁体   English

d3饼图颜色分配给弧

[英]d3 pie chart color assignment to arcs

In this pie-chart fiddle I would like to color the slices based on the data (type and subtype) of my json. 在这个饼图小提琴中,我想根据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. 但是当需要绘制路径时,我无权访问原始的json,因此我可以选择使用哪种颜色。 I can only access what the pie() function returns (ie. value / startAngle / endAngle ) 我只能访问pie()函数返回的内容(即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. 谢谢。

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) 您可以通过将DOM“上移”到绑定到父节点的数据来访问数据:(在设置颜色的函数中)

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/ 在这里更新小提琴: http : //jsfiddle.net/n4rba907/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM