[英]D3 Data join with containers
How do I properly do data joins with wrapper elements on some of the levels? 在某些级别上,如何正确地将数据与包装元素结合在一起? For instance, say I have the data
[[a,b],[x,y]]
and I want to transform it to this: 例如,假设我有数据
[[a,b],[x,y]]
,我想将其转换为:
<wrapper1>
<content1>
<wrapper2>
<content2>a</content2>
</wrapper2>
<wrapper2>
<content2>b</content2>
</wrapper2>
</content1>
</wrapper1>
<wrapper1>
<content1>
<wrapper2>
<content2>x</content2>
</wrapper2>
<wrapper2>
<content2>y</content2>
</wrapper2>
</content1>
</wrapper1>
Is there a standard way to create elements with this structure? 有没有一种标准的方法来创建具有这种结构的元素?
Here is a code that creates that exact tree structure. 这是创建该确切树结构的代码。
The outerSelection
uses as data the outer array, which has 2 elements: [a, b]
and [x, y]
. outerSelection
使用外部数组作为数据,外部数组具有2个元素: [a, b]
和[x, y]
。
Then, the innerSelection
uses as data the inner arrays, each one containing two elements: "a"
and "b"
for the first one and "x"
and "y"
for the second one. 然后,
innerSelection
将内部数组用作数据,每个内部数组包含两个元素:第"a"
元素为"a"
和"b"
,第二个元素为"x"
和"y"
。
Click "Run conde snippet" and look at your console (the console of your browser, which you can expand, not the snippet's one): 点击“运行内容片段”,然后查看您的控制台(您可以扩展浏览器的控制台,而不是该片段的控制台):
var body = d3.select("body"); var data = [ ["a", "b"], ["x", "y"] ]; var outerSelection = body.selectAll(null) .data(data) .enter() .append("wrapper1") .append("content1"); var innerSelection = outerSelection.selectAll(null) .data(function(d) { return d }) .enter() .append("wrapper2") .append("content2") .html(function(d) { return d }) console.log(body.node())
<script src="https://d3js.org/d3.v4.min.js"></script>
You can achieve this by using the d3 'data' function. 您可以使用d3“数据”功能来实现。 As you have two levels of data here, this is how I would do it:
由于这里有两个级别的数据,因此我将这样做:
data = [['a','b'],['x','y']];
d3.select("#div1")
.selectAll("wrapper1")
.data(data)
.enter().append("wrapper1")
.attr("d", function (d) {
d3.select(this)
.selectAll("content1")
.data(d)
.enter().append("content1")
.attr("d", function (d2) {
d3.select(this)
.append("wrapper2")
.append("content2")
.html(d2);
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.