首页 > 解决方案 > 使用 d3.js 加载 csv 数据时出现问题

问题描述

所以我一直在尝试为我自己的项目实现这个2D 可视化,我在加载 CSV 数据而不是随机生成点时遇到问题。我的代码几乎与上面的链接相同,除了这个:

<script>
    let data_points = [];
    d3.csv("mnist2D.csv", function (d) {
        d.forEach(function (d,i) {
            data_points[i] = {
                x: +d.x,
                y: +d.y,
                name: 'Knowledge Element ' + i,
                group: +d.label,
                radius: +d.radius,
                frequency: +d.frequency
            };
        })

    ...remainder of the script

    //d3.csv end
    })
</script>

我在浏览器控制台中返回的错误是

Uncaught TypeError: o.beforesend is undefined
    send 'https://d3js.org/d3.v3.min.js:1'
    n 'https://d3js.org/d3.v3.min.js:1'
    Cn 'https://d3js.org/d3.v3.min.js:1'
    e 'https://d3js.org/d3.v3.min.js:3'
    <anonymous> 'https://...../test2d:22' //Line of the d3.csv call

此代码与不使用 d3-zoom 和工具提示的 3D 版本完美配合,但在此版本中中断。我假设它与 d3.csv 异步有关,但我不是经验丰富的 JS 开发人员,也不知道如何调试这样的问题。使用 d3.js v5 会解决这个问题吗?任何帮助,将不胜感激。太感谢了!

标签: javascriptd3.js

解决方案


很有趣地解决了我自己的问题。切换到 d3 v5 并且加载数据没有问题。

<script>
    // Load in data (asynchronously)
    d3.csv("mnist2D.csv", function (data) {
        return {
            x: +data.x*50,
            y: +data.y*50,
            name: data.name,
            label: +data.label,
            radius: +data.radius,
            frequency: +data.frequency
        };
    }).then(function(data_points) {

    ...remainder of the script

    //d3.csv end
    })
</script>

推荐阅读