Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

Loading D3.js data from a simple JSON string

Most of the examples in gallery load data from TSV files.

How can I convert the following to use a local json variable instead of TSV data?

d3.tsv("data.tsv", function(error, data) {

    var myEntitiesJson = getEntitiesJson(); // <------ use this instead of "data"
    data.forEach(function(d) {
        d.frequency = +d.frequency;
    });

    x.domain(data.map(function(d) { return d.letter; }));
    y.domain([0, d3.max(data, function(d) { return d.frequency; })]);

    ...

    svg.selectAll(".bar")
        .data(data)     // <----- bind to myEntities instead
}

As far as I can tell, I just need to do something to my entitiesJson, in order to data-fy it so that the chart could bind to it.

UPDATE

I am making some progress. I plugged in my entities from JSON and the graph is starting to take new shape.

Currently the following code breaks:

svg.selectAll(".bar")
    .data(myEntities)  // <-- this is an array of objects
    .enter().append("rect")

This is causing:

Error: Invalid value for attribute y="NaN"

Error: Invalid value for attribute height="NaN"

question from:https://stackoverflow.com/questions/15764698/loading-d3-js-data-from-a-simple-json-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

for remote data.json replace :

d3.tsv("data.tsv", function(error, data) {...}

with :

d3.json("data.json", function(error, data) {
    console.log(data); // this is your data
});

for local data:

var myData = { {date:'2013-05-01', frequency:99},
               {date:'2013-05-02', frequency:24} };

function draw(data) {
    console.log(data); // this is your data
}

draw(myData);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...