使用d3.js处理一个多维数据数组

Processing a multidimensional data array with d3.js

本文关键字:一个 数据 数组 js d3 处理 使用      更新时间:2023-09-26

目前我正在学习一些"D3.js",并试图让我的头围绕数据的处理和选择的方式。

我被我为自己创建的以下任务卡住了。

理想情况下,我想要的东西在功能上等同于:

    <svg>
        <circle r=​"20.5" cx=​"100" cy=​"200">​</circle>​
        <circle r=​"20.5" cx=​"300" cy=​"10">​</circle>​
    </svg>

我现在(用我的逻辑)是:

    var matrix = [ [{ "x": 100, "y": 200 }], [{ "x": 300, "y": 10 }]];
    var result = d3.select("body").append("svg")  // Append SVG to end of Body
       .data(matrix) // select this data
       .selectAll("g") //g is a svg grouping tag
       .data(function (d) { return d; }) //Unwrap the first part of the array
       .enter() // Grab all the data that is new to the selection in each array
       .selectAll("g") 
       .data(function (d) { return d;}) // foreach each item inside the 1D array
       .enter() // For all the data that doesn't exist already in the SVG
       .append("circle") // Append Circle to the DOM with the following attributes
       .attr("r", 20.5)
       .attr("cx", function (d) { return d.x; })
       .attr("cy", function (d) { return d.y; });
    };

奇怪的是:

 var result = d3.select("body").append("svg")
        .data(matrix)
        .selectAll("g")         
        .enter()            
        .append("circle")
        .attr("r", 20.5)
        .attr("cx", function (d) { return d.x; })
        .attr("cy", function (d) { return d.y; });
    };

似乎不知何故能够获得数组中的第一项,但不能正确迭代。我不太确定它是如何进入数组的

D3似乎离我习惯的编程范式有很大的距离,而且更难调试,所以如果有人能解释我哪里出错了,那就太棒了。

哦,虽然这个例子是相当无用的,我可以使用合并命令将其扁平化-为了充分理解D3操作的目的。我想画几个圆没有合并:)

谢谢!

看到你提到你是d3的新手,我将对基础知识做一些评论。

首先,我们试图将一些svg元素放在DOM上,所以首先我们必须有一个svg画布来工作。通常它在代码的早期设置,看起来像这样:

var svg = d3.select("body")
             .append("svg")
             .attr("width", 350)
             .attr("height", 250);

请注意,最好为高度和宽度定义变量(但我很懒)。

现在你有了画布,让我们看看d3是如何迭代的。D3在一个数组上迭代,所以你不必在你的例子中有一个数组中的数组,如:

 var matrix = [ { "x": 100, "y": 200 }], [{ "x": 300, "y": 10 }];

现在你的第二个代码块几乎就在那里了,只是稍微重新排列了一下。我们需要做的第一件事是使用svg.selectAll("circle")为svg画布中的圆圈创建占位符。接下来,我们使用data(matrix)将数据引入空占位符,并使用'enter() '进行绑定。现在我们要做的就是给圆圈加上一些属性剩下的代码都是这样做的

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

你可以看到这一切都放在一起,在这个小提琴做了一些小的改变。

如果你想了解d3我建议你去看Scott Murray关于d3的书这是一个很好的介绍

相关文章: