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.
D3. js is a JavaScript library used to manipulate documents based on data. It uses HTML, CSS, and SVG to create visual representations of data which can be viewed on any modern browser. It also provides some awesome features for interactions and animations.
The JavaScript ecosystem has completely changed during this time, in terms of libraries, best practices and even language features. Nevertheless, D3 is still here. And it's more popular than ever.
js, or D3, stands for data-driven documents. It is an open-source JavaScript library that creates interactive data visualizations in a web browser using SVG, HTML, and CSS.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With