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

Why isn' t this selecting and changing the attributes in 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');

其他我试过但没有用的方法

我试过这条线

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

我试过了

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

但两次都收到错误:d3.v7.min.js:2 Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Element': '[object Object]' is not a valid select或.

什么有效但我不想要它

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

因为我想 select 变量 myCircles 的圈子而不是使用 d3 标签“circle”,因为我打算稍后制作更多的圈子。

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


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');

官方 General Update Pattern Tutorial

是我推荐的了解这些细节的好资源

补充:

除了变量,您还可以使用 classes 来区分对象。例如,如果您在圆圈后附加 class,您稍后可以使用 selectAll 仅检索与 class:

匹配的圆圈
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');