D3js won't使用数据数组绘制圆

d3js won't draw circles using data array

本文关键字:数据 数组 绘制 won D3js      更新时间:2023-09-26

我有一个d3js SVG绘图,我做的如下:

d是一个数组,包含像

这样的元素
  var d=[{"x":370,"y":40,"label":"Label 1"},    
        {"x":370,"y":150,"label":"Label 2"} ];

和d3的代码是这样的

    // here el is my HTML element and width/height are sizes
    var svg=d3.select(el).append('svg')
    svg.attr({width: width, height: height});
    // this works just fine
            svg.append("circle") // attach a circle
                .attr("cx", 200) // position the x-center
                .attr("cy", 100) // position the y-center
                .attr("r", 50);
    //  now trying to plot that 'd' array
            svg.data(d)
                .enter().append("circle")
                .attr("cy", function (d) {                    
                    return d.y
                })
                .attr("cx", function (d) {
                    return d.x
                })
                .attr("r", 10);

后一条指令不会生成SVG元素。也没有显示错误。"cy"/"cx"中的函数被调用为ok。

不幸的是,我的d3有点生锈了,但你似乎错过了一个selectAll。试试下面的命令:

svg.selectAll("*").data(d)
    .enter().append("circle")
    .attr("cy", function (d) {                    
        return d.y
    })
    .attr("cx", function (d) {
        return d.x
    })
    .attr("r", 10);

查看这里的jsFiddle,看看它是如何工作的;据我所知,selectAll是用来过滤掉任何可能已经存在的值。即使使用"*"作为CSS选择器,也没有值匹配,因此使用d中的所有项。