【问题标题】:Uncaught TypeError: Cannot read property 'position' of undefined (D3.JS)未捕获的类型错误:无法读取未定义的属性“位置”(D3.JS)
【发布时间】:2014-04-13 03:44:26
【问题描述】:

当我尝试检索 JSON 数据 并将其设为 折线图时弹出此错误。

未捕获的类型错误:无法读取未定义的属性“位置”

这是我的 JS

d3.json("../js/sample2.json", function(data) {
    var canvas = d3.select("body").append("svg")
            .attr("width", 500)
            .attr("height", 500);

    var i = 0;
    var group = canvas.append("g")
            .attr("transform", "translate(100,100");


    var line = d3.svg.line()
            .x(function(d, i) {
                console.log("x" + d[0].position[i]);
                return d[0].position[i];
            })
            .y(function(d, i) {
                console.log("y" + d[1].position[i]);
                return d[1].position[i];
            });

    group.selectAll("path")
            .data([data]).enter()
            .append("path")
            .attr("d", line)
            .attr("fill", "none")
            .attr("stroke", "red")
            .attr("stroke-width", 5);
});

这是我的 JSON:

[{"name": "x", "position":[40,60,80,100] },
 {"name": "y", "position":[70,190,220,160]}
]

My fiddle

有人可以帮我解决这个问题吗?

我希望从 JSON 文件中检索到的数据中显示该行。

【问题讨论】:

    标签: javascript json svg d3.js html5-canvas


    【解决方案1】:

    找到解决方案:

    d3.json("../js/sample2.json", function(data) {
    
        var canvas = d3.select("body").append("svg")
                .attr("width", 500)
                .attr("height", 500);
        console.log(data);
    
        var group = canvas.append("g")
                .attr("transform", "translate(100,100");
    
    
        var line = d3.svg.line()
                .x(function(d, i) {
    //                console.log(data[0].position[i]);
                    return data[0].position[i];
                })
                .y(function(d, i) {
    //                console.log(data[1].position[i]);
                    return data[1].position[i];
                });
    
    
        group.selectAll("path")
                .data([data]).enter()
                .append("path")
                .attr("d", line(data[0].position))
                .attr("fill", "none")
                .attr("stroke", "red")
                .attr("stroke-width", 5);
    });
    
    Had to provide .attr("d", line(data[0].position))
    

    【讨论】:

      猜你喜欢
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多