着色多行我目前组装与数据点内有一定的线图,从格式化像这样JSON对象的数组:D3:从嵌套数据
var data = [{
"name": "metric1",
"datapoints": [
[10.0, 1333519140],
[48.0, 1333519200]
]
}, {
"name": "metric2",
"datapoints": [
[48.0, 1333519200],
[12.0, 1333519260]
]
}]
我想有一个颜色为每个指标,所以我试图根据数组数据中的对象索引 对它们着色。我现在只是把圆圈中的代码如下:
// We bind an svg group to each metric.
var metric_groups = this.vis.selectAll("g.metric_group")
.data(data).enter()
.append("g")
.attr("class", "metric_group");
// Then bind a circle for each datapoint.
var circles = metric_groups.selectAll("circle")
.data(function(d) { return d.datapoints; });
circles.enter().append("circle")
.attr("r", 3.5);
现在,如果我改变,要像最后一位:
circles.enter().append("circle")
.attr("r", 3.5);
.style("fill", function(d,i) { return i%2 ? "red" : "blue"; }
我得到交替的红色和蓝色圆圈,因为可以预期。
以从Nested Selections : 'Nesting and Index'一些建议,我想:
circles.enter().append("circle")
.attr("r", 3.5);
.style("fill", function(d,i,j) { return j%2 ? "red" : "blue"; }
不工作(j是不确定的),大概是因为我们在命名的属性数据点,而不是一个数组元素。如何在不改变数据结构的情况下去做我想要的着色?谢谢!
我通过设置组的样式而不是圆圈解决了这个问题(为什么需要我在堆栈溢出上发布才能想到这一点?)。我仍然很欣赏较少的work-around-y答案(例如,对于组内的圆圈和路径会需要不同样式,或者孩子的属性是无论如何都不能继承的情况)。 – 2012-04-08 23:26:01