d3.js& json - 简单的示例代码? [英] d3.js & json - simple sample code?
问题描述
有一些例子从d3.js中的外部json文件中获取数据。但是这些示例不显示json,所以我真的想看看它是如何工作的。
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.
我有这个json文件test.json,它看起来像
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.
在d3.js脚本中。我添加了到目前为止。
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");
如果我使用此数据集:
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);
我想知道如果我使用外部json文件,我应该如何改变这部分调用数据。我真的很感激有人可以教我这个!非常感谢。
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.json("data.js", function(data) {
alert(data.length)
});
其中data.js或data.json或任何你想调用它只要有js content是你的json文件。也请尝试阅读: https://github.com/mbostock/d3/wiki/Requests 。所有使用json数据的代码都将从json回调函数中调用。
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.
这篇关于d3.js& json - 简单的示例代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!