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
213 views
in Technique[技术] by (71.8m points)

javascript - d3.js & json - simple sample code?

There are some examples to get data from external json file in d3.js. But these samples do not show the json, so I really want to see how it works.

I have this json file test.json, and it looks like

[
    {"a":"-1.14","b":"4.14"},
    {"a":"-0.13","b":"1.38"},
    {"a":"-4.19","b":"1.43"},
    {"a":"-0.21","b":"3.34"}
]

And I want to make a scatterplot with these data.

In the d3.js script. I added so far.

var width = 400;
var height = 400;

var x = d3.scale.linear()
    .domain ([-5, 5])
    .range([0, width]);
var y = d3.scale.linear()
    .domain ([-5, 5])
    .range([0, height]);

var chart = d3.select("body").append("svg")
    .attr("width", width+70)
    .attr("height", height+70)
    .attr("class", chart)
    .append("g")
        .attr("transform", "translate(30, 30)");


chart.selectAll("xline")
    .data(x.ticks(11))
    .enter().append("line")
        .attr("x1", x)
        .attr("x2", x)
        .attr("y1", 0)
        .attr("y2", height)
        .style("stroke", "#ccc");

chart.selectAll("yline")
    .data(y.ticks(11))
    .enter().append("line")
        .attr("y1", y)
        .attr("y2", y)
        .attr("x1", 0)
        .attr("x2", width)
    .style("stroke", "#ccc");

If I use this dataset:

var dataset = [ [-1, -3], [2, 4], [3, -4], [-3, 1]];

I added this and it works fine.

   chart.selectAll("scatter-dots")
      .data(dataset)
      .enter().append("circle")
        .attr("cx", function (d) { return x(d[0]); } )
        .attr("cy", function (d) { return y(d[1]); } )
        .attr("r", 10)
        .style("opacity", 0.6);

I am wondering how I should change this part that calls data, if I use an external json file. I will really appreciate someone can teach me this! Many thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Try something like this

d3.json("data.js", function(data) {
alert(data.length)
});

where data.js or data.json or whatever you want to call it as long as it has js content is your json file. Also try reading: https://github.com/mbostock/d3/wiki/Requests. All your code that uses the json data will be called from the json callback function.


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

...