如何对从外部数据生成的 d3 元素进行分组?



我的行和标签都是从外部数据源生成的。我想要的是将它们的每次迭代放在一个组中,因此代码如下所示:

<g>
<text>Text</text>
<line></line>
</g>
<g>
<text>Text</text>
<line></line>
</g>
<g>
<text>Text</text>
<line></line>
</g>
...
...
...

这是我现在的代码,它将所有元素分组在一个组元素中:

var group = svg.append("g");
var labels = group.selectAll('text')
.data(data)
.enter()
.append('text')
.attr("class", "text")
.attr('x',function (d) { return xScale(d['Untitled']) + 50})
.attr('y',function (d) { return yScale(d['Untitled2']) - 31.2})
.style("text-anchor", "start")
.style("text-decoration", "underline")
.style("cursor", "move")
.text(function(d) { return d.name });
var lines = group.selectAll('line')
.data(data)
.enter()
.append('line')
.attr('class', 'line')
.style("stroke", "#000")
.style("stroke-width", .7)
.attr('x1',function (d) { return xScale(d['Untitled'])})
.attr('y1',function (d) { return yScale(d['Untitled2'])})
.attr('x2',function (d) { return xScale(d['Untitled']) + 50})
.attr('y2',function (d) { return yScale(d['Untitled2']) - 30});

你可以做这样的事情:

const data = [
{ id: 1, value: 10, label: 'aaa' },
{ id: 2, value: 20, label: 'bbb' },
{ id: 3, value: 30, label: 'ccc' }
];
const svg = d3.select('body').append('svg')
.attr('width', 500)
.attr('height', 500);
const g = svg.selectAll('g').data(data, (d) => {
return d.id;
});
const groupEnter = g.enter().append('g');
groupEnter
.append('text')
.text((d) => {
return d.label;
})
groupEnter
.append('line', (d) => {
return d.value;
})

这是一个工作 jsfiddle

基本上,这个想法是获取g.enter().append('g');的返回选择并调用追加两次,第一次追加文本,第二次追加行。

我希望它有所帮助。

最新更新