1 回答
TA贡献1864条经验 获得超6个赞
这是因为数据是嵌套的,所以你需要.merge() scatterGroup 或者在创建之前重新选择它scatterPoints。否则,scatterGroup仍然是空的,而scatterGroup.enter()持有所有的点。
我还.append(g).attr('class', 'scatterPoints')从您的代码中删除了,因为它使用 ag而不是 acircle并且不需要存在
const svg = d3.select('svg');
const color = ['red', 'blue'];
const data = [
[{
x: 10,
y: 10
}, {
x: 40,
y: 100
}],
[{
x: 25,
y: 50
}]
];
const newData = [
[{
x: 10,
y: 20
}, {
x: 50,
y: 100
}],
[{
x: 25,
y: 40
}]
];
function draw(data) {
const scatterGroup = svg.selectAll(".scatterGroup").data(data);
scatterGroup.exit().remove();
const scatterGroupNew = scatterGroup
.enter()
.append("g")
.attr("class", "scatterGroup")
.attr("fill", (d, i) => color[i])
.attr("stroke", (d, i) => color[i]);
// Equivalent:
//const scatterPoints = svg.selectAll(".scatterGroup")
// .selectAll(".scatterPoint")
// .data((d) => d);
const scatterPoints = scatterGroup
.merge(scatterGroupNew)
.selectAll(".scatterPoint")
.data((d) => d);
scatterPoints.exit().remove();
const scatterPointsNew = scatterPoints
.enter()
.append("circle")
.attr("class", "scatterPoint")
.attr("r", 5);
scatterPoints.merge(scatterPointsNew)
.attr("cx", (d, i) => d.x)
.attr("cy", (d, i) => d.y);
}
draw(data);
setTimeout(() => draw(newData), 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
</svg>
添加回答
举报