0

如果这是一个非常基本的问题,请提前道歉。

我正在阅读这本关于 D3 的书,Web 的交互式数据可视化,一个 JavaScript 库
http://chimera.labs.oreilly.com/books/1230000000345/ch06.html#_the_data

我觉得这是一本好书,因为我还是个新手。

在下面的代码和这里的演示中,据我了解,我可以调用“d”任何东西,它仍然会引用“数据集”数组。

无论如何,我的问题是在下面的示例中,如何将 d 引用到数据集数组?如果我有另一个想要引用的数组怎么办?

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3: A simple scatterplot with SVG</title>
        <script type="text/javascript" src="../d3/d3.v3.js"></script>
        <style type="text/css">
            /* No style rules here yet */       
        </style>
    </head>
    <body>
        <script type="text/javascript">

            //Width and height
            var w = 500;
            var h = 100;

            var dataset = [
                            [5, 20], [480, 90], [250, 50], [100, 33], [330, 95],
                            [410, 12], [475, 44], [25, 67], [85, 21], [220, 88]
                          ];

            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            svg.selectAll("circle")
               .data(dataset)
               .enter()
               .append("circle")
               .attr("cx", function(d) {
                    alert(d); //d here can be anything here EG "p" --> still not sure how it relates to dataset --> what if I had another array that I wanted to reference??-->  
                    return d[0];  //return the 0th element
               })
               .attr("cy", function(d) {
                    return d[1];    //return the 1th element
               })
               .attr("r", 5);

        </script>
    </body>
</html>
4

1 回答 1

0

Well that's a good question. First lets go through what your doing in that code. The first part involves selecting the body element of the DOM and appending a svg container, that's in this snippet:

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

Next your creating svg circles based on the data, which in this case the variable dataset. That's done in this snippet:

    svg.selectAll("circle")
       .data(dataset)
       .enter()
       .append("circle")

You then give the circles some attributes in the rest of the code.

So your question how is d referenced to your dataset is answered in the data(dataset) line. This line says, use the variable dataset and bind it to the circles. So if you had another dataset called Hattrick you would simply replace dataset with Hattrick in data(dataset).

I'd suggest that you have a look at these tutorials Thinking with Joins and How Selections Work both by Mike Bostock as well as Scott Murray's excellent book. You might also be interested in Scott's on-line tutorials if you haven't already found them.

于 2013-09-26T03:57:58.280 回答