从子数组d3.js添加元素 [英] Adding elements from subarrays d3.js
问题描述
所以我想把头包裹在d3的选择部分上,我试图通过做一个简单的例子来测试它。
So i'm trying to wrap my head around the selection part of d3 and I was trying to test it by doing a simple example.
我有一个数组
该数组:
var data = [ 37, 36, 31, 46 ];
但是,如果我的数组看起来像这样:
But what if my array looked like this:
var data = [ [37, 36, 31, 46], [24, 32, 55, 23] ];
因此它已经为每个子数组附加了一个 g,但是我将如何添加一个圆和一个文本子数组中每个数字的元素?
So it already appends a "g" for each subarray but how would I add a circle and a text element for each number within the subarray ?
http ://jsfiddle.net/jakob_/c2h6F/1/
var svg = d3.select("svg");
var data = [ 37, 36, 31, 46 ];
var groups = svg.selectAll("g")
.data(data)
.enter()
.append("g")
groups.attr("transform", function(d, i){
var x = 78 * i + 100;
var y = i + 100;
return "translate(" + [x, y] + ")";
})
var circles = groups.append("circle")
.attr({
cx: function(d, i){
return 0
//return i * 40 + 100;
},
cy: function(d, i){
return 0
//return i * 30 + 100;
},
r: function(d, i){
return ((d / Math.PI) / 2) * 5;
},
fill: "red",
})
var label = groups.append("text")
.text(function(d){
return d;
})
.attr({
"alignment-baseline": "middle",
"text-anchor": "middle"
})
推荐答案
在代码的 groups部分中,您可以具有一个附加的data参数,该参数返回绑定到父元素的数据的子数组...例如:
In the groups section of your code, you can have an additional data parameter that returns the subarray of the data bound to the parent element... for example:
var data = [ [37, 36, 31, 46], [24, 32, 55, 23] ];
var groups = svg.selectAll('g')
.data(data)
.enter()
.append('g');
var circles = groups.selectAll('circle')
.data(function(d) { return d; })
.enter()
.append('circle');
var labels = groups.selectAll('text')
.data(function (d) { return d; })
.enter()
.append('text');
当'enter()'函数出现在圆和标签上时,它将在已绑定到父组的数据的子数组。
When the 'enter()' function happens on the circles and labels, it will be iterating through the subarray of the data already bound to the group parent.
这篇关于从子数组d3.js添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!