为什么不选择和更改 D3 中的属性?



我有一个简单的数据对象data,它包含一些半径,坐标和颜色,我希望用于我的圆圈。然而,我现在想把它们都变成橙色,但最后一行代码似乎没有运行?

const myCircles = svg.selectAll()
.data(data);
myCircles.enter().append('circle')
.attr('cx' , (d) => d.x)
.attr('cy' , (d) => d.y)
.attr('r' , (d) => d.radius )
.attr('fill' , (d) => d.color )
myCircles.attr('fill' , 'orange');

我尝试过的其他东西都不起作用

I tried the line

d3.selectAll(myCircles).attr('fill' , 'orange');

And I tried

svg.selectAll(myCircles).attr('fill' , 'orange');

但是两次都收到错误:d3.v7.min.js:2 Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Element': '[object object]'不是一个有效的选择器。

什么工作,但我不希望它

d3.selectAll('circle').attr('fill' , 'orange')

因为我想通过变量myCircles来选择圆圈而不使用d3标签"circle"因为我打算以后画更多的圆。

myCircles变量为空,因为它只是更新选项,而不是添加圆圈的输入选项。如果您需要一个变量来保存附加的圆圈,您可以为它分配enter选项:


const myCircles = svg.selectAll()
.data(data);
const myOrangeCircles = myCircles.enter().append('circle')
.attr('cx' , (d) => d.x)
.attr('cy' , (d) => d.y)
.attr('r' , (d) => d.radius )
.attr('fill' , (d) => d.color )
myOrangeCircles.attr('fill' , 'orange');
我推荐的一个很好的资源是官方的通用更新模式教程 。

补充:

除了变量,还可以使用类来区分对象。例如,如果您在圆圈后面添加了一个类,那么您可以稍后使用selectAll只检索与类匹配的圆圈:

myCircles.enter().append('circle')
.attr('cx' , (d) => d.x)
.attr('cy' , (d) => d.y)
.attr('r' , (d) => d.radius )
.attr('fill' , (d) => d.color )
.classed('myOrangeCircle', true)
svg.selectAll('circle.myOrangeCircle').attr('fill' , 'orange');

最新更新