Javascript d3 csv 数据加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14986435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:34:19  来源:igfitidea点击:

d3 csv data loading

javascripthtmlcsvd3.js

提问by English Grad

I am trying to adapt a simple scatterplot program in D3 to accept a CSV file. When I use the data in the file it works just fine, but when I try to load the CSV file it simply won't work. Is there something simple I am missing? The contents of the CSV file "datatest.csv" are the same as the dataset in the code. I have checked that the browser is loading the data, and it seems to all be there. I figure I'm simply missing a step.

我正在尝试在 D3 中调整一个简单的散点图程序以接受 CSV 文件。当我使用文件中的数据时,它工作得很好,但是当我尝试加载 CSV 文件时,它根本无法工作。我缺少一些简单的东西吗?CSV 文件“datatest.csv”的内容与代码中的数据集相同。我已经检查过浏览器是否正在加载数据,它似乎都在那里。我想我只是错过了一步。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>D3 Demo: Linear scales</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 = 900;
        var h = 500;
        var padding = 20;
        var dataset = [];

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

        d3.csv("datatest.csv", function(data) {
        dataset=data
        });



        //Create scale functions
        var xScale = d3.scale.linear()
                             .domain([0, d3.max(dataset, function(d) { return d[0]; })])
                             .range([padding, w - padding * 2]);

        var yScale = d3.scale.linear()
                             .domain([0, d3.max(dataset, function(d) { return d[1]; })])
                             .range([h - padding, padding]);

        var rScale = d3.scale.linear()
                             .domain([0, d3.max(dataset, function(d) { return d[1]; })])
                             .range([2, 5]);

        //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) {
                return xScale(d[0]);
           })
           .attr("cy", function(d) {
                return yScale(d[1]);
           })
           .attr("r", function(d) {
                return rScale(d[1]);
           });
    </script>
</body>
</html>

This is the content of the CSV file:

这是 CSV 文件的内容:

x-coordinate, y-coordinate
5,20
480,90
250,50
100,33
330,95
410,12
475,44
25,67
85,21
220,88
600,150

采纳答案by meetamit

IMPORTANT:

重要的:

While the answer here works, there's a builtin method d3.csv.parseRows(), which achieves the same result. For that, see @ryanmt's answer (also on this page). However, keep in mind that regardless of the method you use, if your CSV has numbers in it then you'll need to convert them from strings to javascript Numbers. You can do it by prefixing the parsed values with a +. For example, in the solution I provided here — which doesn't use parseRows()— that conversion is achieved via +d["x-coordinate"].

虽然这里的答案有效,但有一个内置方法d3.csv.parseRows(),可以实现相同的结果。为此,请参阅@ryanmt 的回答(也在此页面上)。但是,请记住,无论您使用哪种方法,如果您的 CSV 中有数字,那么您需要将它们从字符串转换为 javascript 数字。您可以通过为解析值添加前缀来实现+。例如,在我在这里提供的解决方案中(不使用parseRows()),转换是通过+d["x-coordinate"].

THE ANSWER:

答案:

The CSV parser produces an array of objects, rather than the array of arrays that you need. It looks like this:

CSV 解析器生成一个对象数组,而不是您需要的数组数组。它看起来像这样:

[
  {"x-coordinate":"5"," y-coordinate":"20"},
  {"x-coordinate":"480"," y-coordinate":"90"},
  {"x-coordinate":"250"," y-coordinate":"50"},
  {"x-coordinate":"100"," y-coordinate":"33"},
  ...
]

To transform it, you need to use a map()function:

要转换它,您需要使用一个map()函数:

d3.csv("datatest.csv", function(data) {
  dataset = data.map(function(d) { return [ +d["x-coordinate"], +d["y-coordinate"] ]; });
});

(Note, map()is not available in older IE. If that matters, then there are plenty of workarounds with d3, jQuery, etc)

(注意,map()在较旧的 IE 中不可用。如果这很重要,那么 d3、jQuery 等有很多解决方法)

回答by Ryanmt

D3 provides a builtin for this very thing.

D3 为这件事提供了一个内置函数。

Instead of calling .parse()on your data, call .parseRows. This provides just the data as an Array, rather than an Object (based upon the header line).

不要调用.parse()您的数据,而是调用.parseRows. 这仅将数据作为数组提供,而不是对象(基于标题行)。

see the Documentation.

请参阅文档

回答by Garfield

Using d3.csvParseRows (assuming D3 v5)

使用 d3.csvParseRows(假设 D3 v5)

d3.text('/data/output.csv')
  .then( text => d3.csvParseRows(text) )
  .then( d => console.log(d) );