2

I've search far and wide, but cannot bind JSON data to a simple scatterplot for the life of me. I've looked at posts and examples, but I can only manage to bind arrays and not JSON. Below, I've tried to simply display JSON data as text and still can't make it work. Please let me know if you have any idea why!

d3_attempt.js

var data;

d3.json("json_data.json",function(error, dataset) {
    if (error) return console.warn(error);

    data = dataset;

    var myscatter = d3.select("#somediv").append("svg")
                    .attr("width", 700)
                    .attr("height", 400);

    myscatter.selectAll("text")
        .data(data.data)
        .enter()
        .append("text")
        .text(function(d){return d)})
});

json_data.json

{
    "data":
    {
        "john": {"name": "john", "age": "13"},
        "matt": {"name": "matt", "age":"14"}
    }
}
4

1 回答 1

2

是的,您只能绑定数组,因此您可能希望将数据转换为数组:

myscatter.selectAll("text")
    .data(d3.values(data.data));

这将为您text的每个节点提供{ name, age }对象作为数据。如果您也需要密钥(在这种情况下看起来不需要),您可以使用d3.entries,它为您提供了一个对象数组,例如{ key: "john", value: { name: "John", age: "13" }}.

于 2013-08-22T16:59:21.800 回答