d3 不会在第一次运行时附加圆圈

我正在使用嵌套数据集和以下代码在 d3 v5 中绘制圆圈:


const scatterGroup = svg.selectAll(".scatterGroup").data(data);


scatterGroup.exit().remove();


scatterGroup

  .enter()

  .append("g")

  .attr("class", "scatterGroup")

  .attr("fill", (d, i) => color[i])

  .attr("stroke", (d, i) => color[i])

  .append("g")

  .attr("class", "scatterPoints");


const scatterPoints = scatterGroup

  .selectAll(".scatterPoints")

  .data((d) => d);


scatterPoints

  .enter()

  .append("circle")

  .attr("class", "scatterPoints")

  .attr("cx", (d, i) => xScale(d.x))

  .attr("cy", (d, i) => yScale(d.y))

  .attr("r", 5);


scatterPoints.exit().remove();


const scatterUpdate = scatterGroup

  .transition()

  .duration(500)

  .attr("fill", (d, i) => color[i])

  .attr("stroke", (d, i) => color[i]);


scatterPoints

  .transition()

  .duration(500)

  .attr("cx", (d, i) => xScale(d.x))

  .attr("cy", (d, i) => yScale(d.y));

在提供数据的第一次运行中没有任何反应。控件在第一次加载时未到达追加圆圈。第二次加载数据时,d3 附加圆圈。谁能告诉我如何在首次提供数据时让它们出现以及为什么会这样?


神不在的星期二
浏览 126回答 1
1回答

慕尼黑的夜晚无繁华

这是因为数据是嵌套的,所以你需要.merge() scatterGroup 或者在创建之前重新选择它scatterPoints。否则,scatterGroup仍然是空的,而scatterGroup.enter()持有所有的点。我还.append(g).attr('class', 'scatterPoints')从您的代码中删除了,因为它使用 ag而不是 acircle并且不需要存在const svg = d3.select('svg');const color = ['red', 'blue'];const data = [&nbsp; [{&nbsp; &nbsp; x: 10,&nbsp; &nbsp; y: 10&nbsp; }, {&nbsp; &nbsp; x: 40,&nbsp; &nbsp; y: 100&nbsp; }],&nbsp; [{&nbsp; &nbsp; x: 25,&nbsp; &nbsp; y: 50&nbsp; }]];const newData = [&nbsp; [{&nbsp; &nbsp; x: 10,&nbsp; &nbsp; y: 20&nbsp; }, {&nbsp; &nbsp; x: 50,&nbsp; &nbsp; y: 100&nbsp; }],&nbsp; [{&nbsp; &nbsp; x: 25,&nbsp; &nbsp; y: 40&nbsp; }]];function draw(data) {&nbsp; const scatterGroup = svg.selectAll(".scatterGroup").data(data);&nbsp; scatterGroup.exit().remove();&nbsp; const scatterGroupNew = scatterGroup&nbsp; &nbsp; .enter()&nbsp; &nbsp; .append("g")&nbsp; &nbsp; .attr("class", "scatterGroup")&nbsp; &nbsp; .attr("fill", (d, i) => color[i])&nbsp; &nbsp; .attr("stroke", (d, i) => color[i]);&nbsp; // Equivalent:&nbsp; //const scatterPoints = svg.selectAll(".scatterGroup")&nbsp; //&nbsp; .selectAll(".scatterPoint")&nbsp; //&nbsp; .data((d) => d);&nbsp; const scatterPoints = scatterGroup&nbsp; &nbsp; .merge(scatterGroupNew)&nbsp; &nbsp; .selectAll(".scatterPoint")&nbsp; &nbsp; .data((d) => d);&nbsp; scatterPoints.exit().remove();&nbsp; const scatterPointsNew = scatterPoints&nbsp; &nbsp; .enter()&nbsp; &nbsp; .append("circle")&nbsp; &nbsp; .attr("class", "scatterPoint")&nbsp; &nbsp; .attr("r", 5);&nbsp; scatterPoints.merge(scatterPointsNew)&nbsp; &nbsp; .attr("cx", (d, i) => d.x)&nbsp; &nbsp; .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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript