而不是现成的数据,我如何从CSV中读取

instead of ready data how can i read from csv?

本文关键字:CSV 读取 数据      更新时间:2023-09-26

我有这段代码,我想用csv中的数据更改静态数据

CSV 如下所示:

GPA,Total Distance,id
3.27,22.0,20032202
2,64.0,20038107
2.81,10.0,20051566
2.33,66.5,20060382

我想在 y 轴上添加 GPA和 X 轴上的总距离

当我尝试从 D3 库添加代码时,它不起作用

<html>
  <head>
  <script src="http://d3js.org/d3.v3.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {
  packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
  var data = new google.visualization.DataTable();
  data.addColumn('number', 'X');
  data.addColumn('number', 'GPA');
  data.addRows([
    [0, 0],
    [1, 10],
    [2, 23],
    [3, 17],
    [4, 18],
  ]);
  var options = {
    hAxis: {
      title: 'Total Distance'
    },
    vAxis: {
      title: 'GPA'
    }
  };
  var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
  chart.draw(data, options);
}
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>

这是我能想出的帮助你的最佳答案。

在你的问题中,你必须在javascript中处理不同的主题

  • 在 JavaScript 中获取本地文件的内容
  • 将此内容解析为 CSV 文件(并使其成为多维数组(
  • 准备要放入图表中的值

首先,添加以下两个库:jQuery用于简化的ajax对文件的调用,jquery-csv用于解析内容的简化方法。

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>

然后,您必须重新路由图表回调:您必须指向一个异步获取文件内容的函数(getFileContent在下面的示例中(。

只有在成功的情况下,您才能将 csv 数据格式化为数组。

只有这样,您才能通过将格式化和排序的数组传递给drawbasic方法,将数据提供给图表。

最后,你最终得到了那个脚本

<script type="text/javascript">
    google.charts.load('current', {
        packages: ['corechart', 'line']
    });
    google.charts.setOnLoadCallback(getFileContent);
    function getFileContent() {
        var filePath = 'file:///path/to/file.csv';
        // 1. Get local file content asynchronously
        $.get(filePath, {}, function (data) {
            console.log(arguments);
            var lines = $.csv.toArrays(data); // 2. Parse the csv as a multidimensional array
            var header = lines.shift(); // 3. Remove the header of the file
            // 4. Sort the lines by the second column
            lines.sort(function (a, b) {
                if (a[1] === b[1]) {
                    return 0;
                }
                else {
                    return (a[1] < b[1]) ? -1 : 1;
                }
            });
            // 5. Pass your lines to the draw method
            drawBasic(lines);
        }, 'text')
                .fail(function () {
                    console.log(arguments);
                })
        ;
    }
    function drawBasic(lines) {
        var data = new google.visualization.DataTable();
        data.addColumn('number', 'X');
        data.addColumn('number', 'GPA');
        for (i = 0; i < lines.length; i++) {
            // 6. Don't forget to parse as float the numbers in the array, they are strings at this point
            // You'll get a 'Type mismatch. Value 3,27 does not match type number' error if you don't
            var xValue = parseFloat(lines[i][1]);
            var yValue = parseFloat(lines[i][0]);
            data.addRow([xValue, yValue]);
        }
        var options = {
            hAxis: {
                title: 'Total Distance'
            },
            vAxis: {
                title: 'GPA'
            }
        };
        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
        chart.draw(data, options);
    }
</script>

不要忘记更改 getFileContent 中的文件路径,前面是 file://

归功于SO中的答案,这些答案帮助我创建了这个答案:

  • Javascript - 读取本地文本文件
  • 如何按列值对二维数组进行排序?

旁注

在不同的条件下,在使用Javascript

显示数据时,通过HTTP调用获得csv(或者,使用Javascript,JSON更好(会更常见。 本地文件读取可以保留用于服务器端处理,使此内容通过 HTTP 可用。